Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
python3 send email via gmail API
from apiclient.discovery import build
from apiclient import errors
from httplib2 import Http
from oauth2client import file, client, tools
from email.mime.text import MIMEText
from base64 import urlsafe_b64encode
SENDER = <sender>
RECIPIENT = <recipient>
SUBJECT = <subject>
CONTENT = <content>
SCOPE = 'https://www.googleapis.com/auth/gmail.compose' # Allows sending only, not reading
# Initialize the object for the Gmail API
# https://developers.google.com/gmail/api/quickstart/python
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPE)
creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))
# https://developers.google.com/gmail/api/guides/sending
def create_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
encoded_message = urlsafe_b64encode(message.as_bytes())
return {'raw': encoded_message.decode()}
# https://developers.google.com/gmail/api/guides/sending
def send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print('Message Id: %s' % message['id'])
return message
#except errors.HttpError, error:
except:
print('An error occurred: %s' % error)
raw_msg = create_message(SENDER, RECIPIENT, SUBJECT, CONTENT)
send_message(service, "me", raw_msg)
@yasoobkhalid1
Copy link

yasoobkhalid1 commented Dec 27, 2018

In line 66, to send an error, we need to import the errors module from googleapiclient. Otherwise, it will return an error saying it doesn't recognize the 'error' variable.

@OneGneissGuy
Copy link

OneGneissGuy commented Jun 23, 2019

Uncomment line 64 to specifically catch an errors.HttpError or change line 66 to:

print('An error occurred')

@av-guy
Copy link

av-guy commented Jan 4, 2020

Thanks for this; it helped me with creating the message body.

@Mgregchi
Copy link

Mgregchi commented Aug 29, 2020

Hello, please I really need help with implementing this most especially, what really is "Authorized Gmail API service instance"? Can someone please give me a simple answer because I have searched even Google API doc still uses that term without explaining and answers from stackoverflow isn't helpful either... And I get "no module named oauth2client" though I followed this https://developers.google.com/gmail/api/quickstart/python
Yes I was authenticated successfully, but trying to send mail with the code hosted above isn't working. Any help please, thanks.

@akulsharma1
Copy link

akulsharma1 commented Feb 3, 2022

Were you able to figure it out @Mgregchi ?

@Panache1
Copy link

Panache1 commented Mar 8, 2022

I used
from googleapiclient.errors import HttpError
except HttpError as error:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment