Skip to content

Commit 3b5f480

Browse files
RajeshGovosanjuktaghosh7Manvendra-P-Singh
authored
Gmail create draft attach (googleworkspace#171)
* git-on-borg files of gmail-api-snippets * Update build.gradle test12 * Update build.gradle * Create Draft with attachment gmail snippet Co-authored-by: sanjuktaghosh7 <sanjuktaghosh@google.com> Co-authored-by: Manvendra-P-Singh <singhmanvendra@google.com>
1 parent d225911 commit 3b5f480

1 file changed

Lines changed: 122 additions & 0 deletions

File tree

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
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_create_draft_with_attachment]
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.Gmail;
22+
import com.google.api.services.gmail.GmailScopes;
23+
import com.google.api.services.gmail.model.Draft;
24+
import com.google.api.services.gmail.model.Message;
25+
import com.google.auth.http.HttpCredentialsAdapter;
26+
import com.google.auth.oauth2.GoogleCredentials;
27+
import org.apache.commons.codec.binary.Base64;
28+
29+
import javax.activation.DataHandler;
30+
import javax.activation.DataSource;
31+
import javax.activation.FileDataSource;
32+
import javax.mail.MessagingException;
33+
import javax.mail.Multipart;
34+
import javax.mail.Session;
35+
import javax.mail.internet.InternetAddress;
36+
import javax.mail.internet.MimeBodyPart;
37+
import javax.mail.internet.MimeMessage;
38+
import javax.mail.internet.MimeMultipart;
39+
import java.io.ByteArrayOutputStream;
40+
import java.io.File;
41+
import java.io.IOException;
42+
import java.util.Collections;
43+
import java.util.Properties;
44+
45+
/* Class to demonstrate the use of Gmail Create Draft with attachment API */
46+
public class CreateDraftWithAttachment {
47+
/**
48+
* Create a draft email.
49+
*
50+
* @param fromEmailAddress - Email address to appear in the from: header.
51+
* @param toEmailAddress - Email address of the recipient.
52+
* @param file - Path to the file to be attached.
53+
* @return the created draft
54+
* @throws MessagingException - if a wrongly formatted address is encountered.
55+
* @throws IOException - if service account credentials file not found.
56+
*/
57+
public static Draft createDraftMessageWithAttachment(String fromEmailAddress,
58+
String toEmailAddress,
59+
File file)
60+
throws MessagingException, IOException {
61+
// Load pre-authorized user credentials from the environment.
62+
// TODO(developer) - See https://developers.google.com/identity for
63+
// guides on implementing OAuth2 for your application.
64+
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(Collections.singletonList(GmailScopes.GMAIL_COMPOSE));
65+
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
66+
credentials);
67+
68+
// Create the gmail API client
69+
Gmail service = new Gmail.Builder(new NetHttpTransport(),
70+
GsonFactory.getDefaultInstance(),
71+
requestInitializer)
72+
.setApplicationName("Gmail samples")
73+
.build();
74+
75+
// Create the email content
76+
String messageSubject = "Test message";
77+
String bodyText = "lorem ipsum.";
78+
79+
// Encode as MIME message
80+
Properties props = new Properties();
81+
Session session = Session.getDefaultInstance(props, null);
82+
MimeMessage email = new MimeMessage(session);
83+
email.setFrom(new InternetAddress(fromEmailAddress));
84+
email.addRecipient(javax.mail.Message.RecipientType.TO,
85+
new InternetAddress(toEmailAddress));
86+
email.setSubject(messageSubject);
87+
88+
MimeBodyPart mimeBodyPart = new MimeBodyPart();
89+
mimeBodyPart.setContent(bodyText, "text/plain");
90+
Multipart multipart = new MimeMultipart();
91+
multipart.addBodyPart(mimeBodyPart);
92+
mimeBodyPart = new MimeBodyPart();
93+
DataSource source = new FileDataSource(file);
94+
mimeBodyPart.setDataHandler(new DataHandler(source));
95+
mimeBodyPart.setFileName(file.getName());
96+
multipart.addBodyPart(mimeBodyPart);
97+
email.setContent(multipart);
98+
99+
// Encode and wrap the MIME message into a gmail message
100+
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
101+
email.writeTo(buffer);
102+
byte[] rawMessageBytes = buffer.toByteArray();
103+
String encodedEmail = Base64.encodeBase64URLSafeString(rawMessageBytes);
104+
Message message = new Message();
105+
message.setRaw(encodedEmail);
106+
107+
try {
108+
// Create the draft message
109+
Draft draft = new Draft();
110+
draft.setMessage(message);
111+
draft = service.users().drafts().create("me", draft).execute();
112+
System.out.println("Draft id: " + draft.getId());
113+
System.out.println(draft.toPrettyString());
114+
return draft;
115+
} catch (GoogleJsonResponseException e) {
116+
// TODO(developer) - handle error appropriately
117+
System.err.println("Unable to create draft: " + e.getDetails());
118+
throw e;
119+
}
120+
}
121+
}
122+
// [END gmail_create_draft_with_attachment]

0 commit comments

Comments
 (0)