7. Sending Mail via GMail API
7. Sending Mail via GMail API
Goto APIs & Services from the left pane then select Enabled API & Services.
Then select Enable API & Services
Search for Gmail * Then select Enable
Create a new python file inside gmail _api/ titled send _ mail.py:
'''
This module sends emails with attachments to the participants
Reference - https://developers.google.com/gmail/api/quickstart/python
'''
import os
def aunthentication():
creds = None
# The file token.json stores the user's access and refresh tokens,
and is
# created automatically when the authorization flow completes for the
first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json',
SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'client_secrets.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
return creds
try:
# Call the Gmail API
service = build('gmail', 'v1', credentials=creds)
#create message
msg = create_message('anubhav.patrick@giindia.com', recipient,
subject, message_text)
send_message(service, 'me', msg)
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['from'] = sender
message['to'] = to
message['subject'] = subject
return {'raw':
base64.urlsafe_b64encode(message.as_string().encode()).decode()}
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 HttpError as error:
print('An error occurred: %s' % error)
Run the python file. At the first time you will be prompted to enter you
Google account credentials. Use the same credentials that you used
to sign up in Google Cloud.