Skip to content

Commit 9569003

Browse files
anuraggooglerRajeshGovosqrrrl
authored
Create and send an email message with and without attachment (googleworkspace#258)
* Create and send an email message with and without attachment Co-authored-by: Rajesh Mudaliyar <[email protected]> Co-authored-by: Steve Bazyl <[email protected]>
1 parent f7835fb commit 9569003

2 files changed

Lines changed: 167 additions & 0 deletions

File tree

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

0 commit comments

Comments
 (0)