1+ // Copyright 2022 Google LLC
2+ //
3+ // Licensed under the Apache License, Version 2.0 (the "License");
4+ // you may not use this file except in compliance with the License.
5+ // You may obtain a copy of the License at
6+ //
7+ // https://www.apache.org/licenses/LICENSE-2.0
8+ //
9+ // Unless required by applicable law or agreed to in writing, software
10+ // distributed under the License is distributed on an "AS IS" BASIS,
11+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+ // See the License for the specific language governing permissions and
13+ // limitations under the License.
14+
15+
16+ // [START gmail_send_message]
17+ import com .google .api .client .googleapis .json .GoogleJsonResponseException ;
18+ import com .google .api .client .http .HttpRequestInitializer ;
19+ import com .google .api .client .http .javanet .NetHttpTransport ;
20+ import com .google .api .client .json .gson .GsonFactory ;
21+ import com .google .api .services .gmail .GmailScopes ;
22+ import com .google .auth .http .HttpCredentialsAdapter ;
23+ import com .google .auth .oauth2 .GoogleCredentials ;
24+ import org .apache .commons .codec .binary .Base64 ;
25+ import com .google .api .services .gmail .Gmail ;
26+ import com .google .api .services .gmail .model .Message ;
27+
28+ import java .io .ByteArrayOutputStream ;
29+ import java .io .IOException ;
30+ import java .util .Collections ;
31+ import java .util .Properties ;
32+
33+ import javax .mail .MessagingException ;
34+ import javax .mail .Session ;
35+ import javax .mail .internet .InternetAddress ;
36+ import javax .mail .internet .MimeMessage ;
37+
38+ /* Class to demonstrate the use of Gmail Send Message API */
39+ public class SendMessage {
40+ /**
41+ * Send an email from the user's mailbox to its recipient.
42+ *
43+ * @param fromEmailAddress - Email address to appear in the from: header
44+ * @param toEmailAddress - Email address of the recipient
45+ * @return the sent message
46+ * @throws MessagingException - if a wrongly formatted address is encountered.
47+ * @throws IOException - if service account credentials file not found.
48+ */
49+ public static Message sendEmail (String fromEmailAddress ,
50+ String toEmailAddress )
51+ throws MessagingException , IOException {
52+ // Load pre-authorized user credentials from the environment.
53+ // TODO(developer) - See https://developers.google.com/identity for
54+ // guides on implementing OAuth2 for your application.
55+ GoogleCredentials credentials = GoogleCredentials .getApplicationDefault ().createScoped (Collections .singletonList (GmailScopes .GMAIL_SEND ));
56+ HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter (
57+ credentials );
58+
59+ // Create the gmail API client
60+ Gmail service = new Gmail .Builder (new NetHttpTransport (),
61+ GsonFactory .getDefaultInstance (),
62+ requestInitializer )
63+ .setApplicationName ("Gmail samples" )
64+ .build ();
65+
66+ // Create the email content
67+ String messageSubject = "Test message" ;
68+ String bodyText = "lorem ipsum." ;
69+
70+ // Encode as MIME message
71+ Properties props = new Properties ();
72+ Session session = Session .getDefaultInstance (props , null );
73+ MimeMessage email = new MimeMessage (session );
74+ email .setFrom (new InternetAddress (fromEmailAddress ));
75+ email .addRecipient (javax .mail .Message .RecipientType .TO ,
76+ new InternetAddress (toEmailAddress ));
77+ email .setSubject (messageSubject );
78+ email .setText (bodyText );
79+
80+ // Encode and wrap the MIME message into a gmail message
81+ ByteArrayOutputStream buffer = new ByteArrayOutputStream ();
82+ email .writeTo (buffer );
83+ byte [] rawMessageBytes = buffer .toByteArray ();
84+ String encodedEmail = Base64 .encodeBase64URLSafeString (rawMessageBytes );
85+ Message message = new Message ();
86+ message .setRaw (encodedEmail );
87+
88+ try {
89+ // Create send message
90+ message = service .users ().messages ().send ("me" , message ).execute ();
91+ System .out .println ("Message id: " + message .getId ());
92+ System .out .println (message .toPrettyString ());
93+ return message ;
94+ } catch (GoogleJsonResponseException e ) {
95+ // TODO(developer) - handle error appropriately
96+ System .err .println ("Unable to send message: " + e .getDetails ());
97+ throw e ;
98+ }
99+ }
100+ }
101+ // [END gmail_send_message]
0 commit comments