Skip to content

Commit 7bd49c2

Browse files
RajeshGovosqrrrlanuraggoogler
authored
Gmail patch createmsg (googleworkspace#251)
* created create_draft_with_attachment.py to create and insert a draft email with attachment * created create_draft.py to create and insert a draft email with attachment Co-authored-by: Steve Bazyl <sqrrrl@gmail.com> Co-authored-by: anuraggoogler <aanursharm@google.com>
1 parent d22e47e commit 7bd49c2

2 files changed

Lines changed: 180 additions & 0 deletions

File tree

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
"""
2+
Copyright 2019 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
16+
"""
17+
# [START gmail_create_draft]
18+
19+
from __future__ import print_function
20+
21+
import base64
22+
from email.mime.text import MIMEText
23+
24+
import google.auth
25+
from googleapiclient.discovery import build
26+
from googleapiclient.errors import HttpError
27+
28+
29+
def gmail_create_draft():
30+
"""Create and insert a draft email.
31+
Print the returned draft's message and id.
32+
Returns: Draft object, including draft id and message meta data.
33+
34+
Load pre-authorized user credentials from the environment.
35+
TODO(developer) - See https://developers.google.com/identity
36+
for guides on implementing OAuth2 for the application.
37+
"""
38+
creds, _ = google.auth.default()
39+
40+
try:
41+
# create gmail api client
42+
service = build('gmail', 'v1', credentials=creds)
43+
44+
message = MIMEText('This is automated draft mail')
45+
message['to'] = 'gduser1@workspacesamples.dev'
46+
message['from'] = 'gduser2@workspacesamples.dev'
47+
message['subject'] = 'Automated draft'
48+
encoded_message = base64.urlsafe_b64encode(message.as_string().encode()
49+
).decode()
50+
51+
create_message = {
52+
'message': {
53+
'raw': encoded_message
54+
}
55+
}
56+
# pylint: disable=E1101
57+
draft = service.users().drafts().create(userId="me",
58+
body=create_message).execute()
59+
60+
print(F'Draft id: {draft["id"]}\nDraft message: {draft["message"]}')
61+
62+
except HttpError as error:
63+
print(F'An error occurred: {error}')
64+
draft = None
65+
66+
return draft
67+
68+
69+
if __name__ == '__main__':
70+
gmail_create_draft()
71+
# [END gmail_create_draft]
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
"""Copyright 2019 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+
http://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+
# [START gmail_create_draft_with_attachment]
16+
17+
from __future__ import print_function
18+
19+
import base64
20+
import mimetypes
21+
import os
22+
from email.mime.audio import MIMEAudio
23+
from email.mime.base import MIMEBase
24+
from email.mime.image import MIMEImage
25+
from email.mime.multipart import MIMEMultipart
26+
from email.mime.text import MIMEText
27+
28+
import google.auth
29+
from googleapiclient.discovery import build
30+
from googleapiclient.errors import HttpError
31+
32+
33+
def gmail_create_draft_with_attachment():
34+
"""Create and insert a draft email with attachment.
35+
Print the returned draft's message and id.
36+
Returns: Draft object, including draft id and message meta data.
37+
38+
Load pre-authorized user credentials from the environment.
39+
TODO(developer) - See https://developers.google.com/identity
40+
for guides on implementing OAuth2 for the application.
41+
"""
42+
creds, _ = google.auth.default()
43+
44+
try:
45+
# create gmail api client
46+
service = build('gmail', 'v1', credentials=creds)
47+
mime_message = MIMEMultipart()
48+
mime_message['to'] = 'gduser1@workspacesamples.dev'
49+
mime_message['from'] = 'gduser2@workspacesamples.dev'
50+
mime_message['subject'] = 'sample with attachment'
51+
text_part = MIMEText('Hi, this is automated mail with attachment.'
52+
'Please do not reply.')
53+
mime_message.attach(text_part)
54+
image_attachment = build_file_part(file='photo.jpg')
55+
mime_message.attach(image_attachment)
56+
encoded_message = base64.urlsafe_b64encode(mime_message.as_string()
57+
.encode()).decode()
58+
59+
create_draft_request_body = {
60+
'message': {
61+
'raw': encoded_message
62+
}
63+
}
64+
# pylint: disable=E1101
65+
draft = service.users().drafts().create(userId="me",
66+
body=create_draft_request_body)\
67+
.execute()
68+
print(F'Draft id: {draft["id"]}\nDraft message: {draft["message"]}')
69+
except HttpError as error:
70+
print(F'An error occurred: {error}')
71+
draft = None
72+
return draft
73+
74+
75+
def build_file_part(file):
76+
"""Creates a MIME part for a file.
77+
78+
Args:
79+
file: The path to the file to be attached.
80+
81+
Returns:
82+
A MIME part that can be attached to a message.
83+
"""
84+
content_type, encoding = mimetypes.guess_type(file)
85+
86+
if content_type is None or encoding is not None:
87+
content_type = 'application/octet-stream'
88+
main_type, sub_type = content_type.split('/', 1)
89+
if main_type == 'text':
90+
with open(file, 'rb'):
91+
msg = MIMEText('r', _subtype=sub_type)
92+
elif main_type == 'image':
93+
with open(file, 'rb'):
94+
msg = MIMEImage('r', _subtype=sub_type)
95+
elif main_type == 'audio':
96+
with open(file, 'rb'):
97+
msg = MIMEAudio('r', _subtype=sub_type)
98+
else:
99+
with open(file, 'rb'):
100+
msg = MIMEBase(main_type, sub_type)
101+
msg.set_payload(file.read())
102+
filename = os.path.basename(file)
103+
msg.add_header('Content-Disposition', 'attachment', filename=filename)
104+
return msg
105+
106+
107+
if __name__ == '__main__':
108+
gmail_create_draft_with_attachment()
109+
# [END gmail_create_draft_with_attachment]

0 commit comments

Comments
 (0)