|
| 1 | +import httplib2 |
| 2 | +import os |
| 3 | +import oauth2client |
| 4 | +from oauth2client import client, tools |
| 5 | +import base64 |
| 6 | +from email.mime.multipart import MIMEMultipart |
| 7 | +from email.mime.text import MIMEText |
| 8 | +from apiclient import errors, discovery |
| 9 | +import mimetypes |
| 10 | +from email.mime.image import MIMEImage |
| 11 | +from email.mime.audio import MIMEAudio |
| 12 | +from email.mime.base import MIMEBase |
| 13 | + |
| 14 | +SCOPES = 'https://www.googleapis.com/auth/gmail.send' |
| 15 | +CLIENT_SECRET_FILE = 'client_secret.json' |
| 16 | +APPLICATION_NAME = 'Gmail API Python Send Email' |
| 17 | + |
| 18 | +def get_credentials(): |
| 19 | + home_dir = os.path.expanduser('~') |
| 20 | + credential_dir = os.path.join(home_dir, '.credentials') |
| 21 | + if not os.path.exists(credential_dir): |
| 22 | + os.makedirs(credential_dir) |
| 23 | + credential_path = os.path.join(credential_dir, |
| 24 | + 'gmail-python-email-send.json') |
| 25 | + store = oauth2client.file.Storage(credential_path) |
| 26 | + credentials = store.get() |
| 27 | + if not credentials or credentials.invalid: |
| 28 | + flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) |
| 29 | + flow.user_agent = APPLICATION_NAME |
| 30 | + credentials = tools.run_flow(flow, store) |
| 31 | + print 'Storing credentials to ' + credential_path |
| 32 | + return credentials |
| 33 | + |
| 34 | +def SendMessage(sender, to, subject, msgHtml, msgPlain, attachmentFile=None): |
| 35 | + credentials = get_credentials() |
| 36 | + http = credentials.authorize(httplib2.Http()) |
| 37 | + service = discovery.build('gmail', 'v1', http=http) |
| 38 | + if attachmentFile: |
| 39 | + message1 = createMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile) |
| 40 | + else: |
| 41 | + message1 = CreateMessageHtml(sender, to, subject, msgHtml, msgPlain) |
| 42 | + result = SendMessageInternal(service, "me", message1) |
| 43 | + return result |
| 44 | + |
| 45 | +def SendMessageInternal(service, user_id, message): |
| 46 | + try: |
| 47 | + message = (service.users().messages().send(userId=user_id, body=message).execute()) |
| 48 | + print 'Message Id: %s' % message['id'] |
| 49 | + return message |
| 50 | + except errors.HttpError, error: |
| 51 | + print 'An error occurred: %s' % error |
| 52 | + return "Error" |
| 53 | + return "OK" |
| 54 | + |
| 55 | +#Create Mail With AttAchment Remove hash to make the code readable |
| 56 | +#def createMessageWithAttachment( |
| 57 | +# sender, to, subject, msgHtml, msgPlain, attachmentFile): |
| 58 | + """Create a message for an email. |
| 59 | +
|
| 60 | + Args: |
| 61 | + sender: Email address of the sender. |
| 62 | + to: Email address of the receiver. |
| 63 | + subject: The subject of the email message. |
| 64 | + msgHtml: Html message to be sent |
| 65 | + msgPlain: Alternative plain text message for older email clients |
| 66 | + attachmentFile: The path to the file to be attached. |
| 67 | +
|
| 68 | + Returns: |
| 69 | + An object containing a base64url encoded email object. |
| 70 | + """ |
| 71 | +# message = MIMEMultipart('mixed') |
| 72 | +# message['to'] = to |
| 73 | +# message['from'] = sender |
| 74 | +# message['subject'] = subject |
| 75 | + |
| 76 | +# messageA = MIMEMultipart('alternative') |
| 77 | +# messageR = MIMEMultipart('related') |
| 78 | + |
| 79 | +# messageR.attach(MIMEText(msgHtml, 'html')) |
| 80 | +# messageA.attach(MIMEText(msgPlain, 'plain')) |
| 81 | +# messageA.attach(messageR) |
| 82 | + |
| 83 | +# message.attach(messageA) |
| 84 | + |
| 85 | +# print "create_message_with_attachment: file:", attachmentFile |
| 86 | +# content_type, encoding = mimetypes.guess_type(attachmentFile) |
| 87 | + |
| 88 | +# if content_type is None or encoding is not None: |
| 89 | +# content_type = 'application/octet-stream' |
| 90 | +# main_type, sub_type = content_type.split('/', 1) |
| 91 | +# if main_type == 'text': |
| 92 | +# fp = open(attachmentFile, 'rb') |
| 93 | +# msg = MIMEText(fp.read(), _subtype=sub_type) |
| 94 | +# fp.close() |
| 95 | +# elif main_type == 'image': |
| 96 | +# fp = open(attachmentFile, 'rb') |
| 97 | +# msg = MIMEImage(fp.read(), _subtype=sub_type) |
| 98 | +# fp.close() |
| 99 | +# elif main_type == 'audio': |
| 100 | +# fp = open(attachmentFile, 'rb') |
| 101 | +# msg = MIMEAudio(fp.read(), _subtype=sub_type) |
| 102 | +# fp.close() |
| 103 | +# else: |
| 104 | +# fp = open(attachmentFile, 'rb') |
| 105 | +# msg = MIMEBase(main_type, sub_type) |
| 106 | +# msg.set_payload(fp.read()) |
| 107 | +# fp.close() |
| 108 | +# filename = os.path.basename(attachmentFile) |
| 109 | +# msg.add_header('Content-Disposition', 'attachment', filename=filename) |
| 110 | +# message.attach(msg) |
| 111 | + |
| 112 | +# return {'raw': base64.urlsafe_b64encode(message.as_string())} |
| 113 | + |
| 114 | + |
| 115 | +def CreateMessageHtml(sender, to, subject, msgHtml, msgPlain): |
| 116 | + msg = MIMEMultipart('alternative') |
| 117 | + msg['Subject'] = subject |
| 118 | + msg['From'] = sender |
| 119 | + msg['To'] = to |
| 120 | + msg.attach(MIMEText(msgPlain, 'plain')) |
| 121 | + msg.attach(MIMEText(msgHtml, 'html')) |
| 122 | + return {'raw': base64.urlsafe_b64encode(msg.as_string())} |
| 123 | +def main(): |
| 124 | + to = input("Enter Email Address: ") |
| 125 | + sender = input("Your Mail ID: ") |
| 126 | + subject = input("Enter your Subject: ") |
| 127 | + msgHtml = input("Enter your Message: ") |
| 128 | + msgPlain = "Hi\nPlain Email" |
| 129 | + SendMessage(sender, to, subject, msgHtml, msgPlain) |
| 130 | + # Send message with attachment: |
| 131 | + #SendMessage(sender, to, subject, msgHtml, msgPlain, '/path/to/file.pdf') |
| 132 | + |
| 133 | +if __name__ == '__main__': |
| 134 | + main() |
0 commit comments