|
| 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