Last active
April 9, 2018 23:39
-
-
Save Julian-Nash/428503b040047f49a40825f83ce152b0 to your computer and use it in GitHub Desktop.
Python 3 gmail API example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Follow guide on https://developers.google.com/gmail/api/quickstart/python to obtain credentials | |
import httplib2 | |
import os | |
import oauth2client | |
from oauth2client import client, tools | |
import base64 | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from apiclient import errors, discovery | |
SCOPES = 'https://www.googleapis.com/auth/gmail.send' | |
CLIENT_SECRET_FILE = 'client_secret.json' | |
APPLICATION_NAME = 'Gmail API Python Send Email' | |
def get_credentials(): | |
home_dir = os.path.expanduser('~') | |
credential_dir = os.path.join(home_dir, '.credentials') | |
if not os.path.exists(credential_dir): | |
os.makedirs(credential_dir) | |
credential_path = os.path.join(credential_dir, 'gmail-python-email-send.json') | |
store = oauth2client.file.Storage(credential_path) | |
credentials = store.get() | |
if not credentials or credentials.invalid: | |
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) | |
flow.user_agent = APPLICATION_NAME | |
credentials = tools.run_flow(flow, store) | |
print('Storing credentials to ' + credential_path) | |
return credentials | |
def SendMessage(sender, to, subject, msgHtml, msgPlain): | |
credentials = get_credentials() | |
http = credentials.authorize(httplib2.Http()) | |
service = discovery.build('gmail', 'v1', http=http) | |
message1 = CreateMessage(sender, to, subject, msgHtml, msgPlain) | |
SendMessageInternal(service, "me", message1) | |
def SendMessageInternal(service, user_id, message): | |
try: | |
message = (service.users().messages().send(userId=user_id, body=message).execute()) | |
print('Message Id: %s' % message['id']) | |
return message | |
except errors.HttpError as error: | |
print('An error occurred: %s' % error) | |
def CreateMessage(sender, to, subject, msgHtml, msgPlain): | |
msg = MIMEMultipart('alternative') | |
msg['Subject'] = subject | |
msg['From'] = sender | |
msg['To'] = to | |
msg.attach(MIMEText(msgPlain, 'plain')) | |
msg.attach(MIMEText(msgHtml, 'html')) | |
raw = base64.urlsafe_b64encode(msg.as_bytes()) | |
raw = raw.decode() | |
body = {'raw': raw} | |
return body | |
def send_email(): | |
to = "[email protected]" | |
sender="[email protected]" | |
subject="Email from Python" | |
msgHtml = "<h3>Hello from Python!</h3>" | |
msgPlain = "" | |
SendMessage(sender, to, subject, msgHtml, msgPlain) | |
print("email sent") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment