| 1 | # based on https://developers.google.com/gmail/api/quickstart/python
 | 
| 2 | import httplib2
 | 
| 3 | import os
 | 
| 4 | import oauth2client
 | 
| 5 | from oauth2client import client, tools, file
 | 
| 6 | import base64
 | 
| 7 | from email.mime.multipart import MIMEMultipart
 | 
| 8 | from email.mime.text import MIMEText
 | 
| 9 | from apiclient import errors, discovery
 | 
| 10 | 
 | 
| 11 | 
 | 
| 12 | ''' scopes
 | 
| 13 | https://mail.google.com/
 | 
| 14 | https://www.googleapis.com/auth/gmail.modify
 | 
| 15 | https://www.googleapis.com/auth/gmail.compose
 | 
| 16 | https://www.googleapis.com/auth/gmail.send
 | 
| 17 | '''
 | 
| 18 | 
 | 
| 19 | CLIENT_SECRET_FILE = 'API_credentials.json'
 | 
| 20 | 
 | 
| 21 | 
 | 
| 22 | def get_credentials(access):
 | 
| 23 |     #print(access)
 | 
| 24 |     home_dir = os.path.dirname(os.path.realpath(__file__))
 | 
| 25 |     credential_dir = os.path.join(home_dir, '.credentials')
 | 
| 26 | 
 | 
| 27 |     credential_path = os.path.join(credential_dir, 'user_specific.json')
 | 
| 28 |     store = oauth2client.file.Storage(credential_path)
 | 
| 29 |     credentials = store.get()
 | 
| 30 | 
 | 
| 31 |     return credentials
 | 
| 32 | 
 | 
| 33 | 
 | 
| 34 | def SendMessage(sender, to, bcc_email, subject, msgHtml, access):
 | 
| 35 |     credentials = get_credentials(access)
 | 
| 36 |     http = credentials.authorize(httplib2.Http())
 | 
| 37 |     service = discovery.build('gmail', 'v1', http=http)
 | 
| 38 |     message1 = CreateMessage(sender, to, bcc_email, subject, msgHtml
 | 
| 39 |                              )
 | 
| 40 |     SendMessageInternal(service, "me", message1)
 | 
| 41 | 
 | 
| 42 | 
 | 
| 43 | def SendMessageInternal(service, user_id, message):
 | 
| 44 |     try:
 | 
| 45 |         message = (service.users().messages().send(userId=user_id, body=message).execute())
 | 
| 46 |         print('Message Id: %s' % message['id'], 'sent')
 | 
| 47 |         return message
 | 
| 48 |     except errors.HttpError as error:
 | 
| 49 |         print('An error occurred: %s' % error)
 | 
| 50 | 
 | 
| 51 | 
 | 
| 52 | def CreateMessage(sender, to, bcc_email, subject, msgHtml):
 | 
| 53 |     msg = MIMEMultipart('alternative')
 | 
| 54 |     msg['Subject'] = subject
 | 
| 55 |     msg['From'] = sender
 | 
| 56 |     msg['To'] = to
 | 
| 57 |     msg['Bcc'] = bcc_email
 | 
| 58 |     msg.attach(MIMEText(msgHtml, 'html'))
 | 
| 59 |     raw = base64.urlsafe_b64encode(msg.as_bytes())
 | 
| 60 |     raw = raw.decode()
 | 
| 61 |     body = {'raw': raw}
 | 
| 62 |     return body
 |