To automatically send an email with an attachment using the Gmail API in Python

This time, I will write about how to automatically send an email with an attachment using Python and the Gmail API.

Send Gmail with Python code

I will write the code to send an email with an attachment. Attach files will be "Hello .txt" under the document directory. Please create the attached file in advance.

The completed form of the code is as follows.

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import base64
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from apiclient import errors
from os.path import basename

#Set scope for Gmail API
SCOPES = ['https://www.googleapis.com/auth/gmail.send']

#Create email content
msg = MIMEMultipart()

#Creating email body
def create_message(sender, to_email, subject, message_text):
    #Email destination
    msg['to'] = to_email
    #Email sender
    msg['from'] = sender
    #Email title(subject)
    msg['subject'] = subject
    #Attach file
    msg.attach(MIMEText(message_text))
    
    encode_message = base64.urlsafe_b64encode(msg.as_bytes())
    return {'raw': encode_message.decode()}

#Sending an email
def send_message(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)

#Main processing
def main():
    #Obtaining an access token
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('gmail', 'v1', credentials=creds)
    #Creating email body
    sender = '*****@gmail.com' #Sender's address
    to_email = '*****@gmail.com' #Recipient's address
    subject = 'Email sending automation test'
    message_text = 'We are testing the automation of email transmission.'
    
    #Attach file
    path = "Documents/Hello.txt"
    with open(path, "rb") as f:
        part = MIMEApplication(
            f.read(),
            Name=basename(path)
        )
    part['Content-Disposition'] = 'attachment; filename="%s"' % basename(path)
    msg.attach(part)
    
        
    message = create_message(sender, to_email, subject, message_text)
    #Call the Gmail API to send an email
    send_message(service, 'me', message)

#Program execution
if __name__ == '__main__':
    main()

Program execution

When you run the above program, the Google account selection screen will appear for the first time. So, please select the account to send the email.

When you select an account, a dialog will appear asking if you want to allow Gmail usage permission, so click Allow.

A confirmation screen for your selection will appear, so click Allow in the same way.

When the user authenticates, the message "The authentication flow has completed, you may close this window." Is displayed in the browser.

This completes the email transmission. Please check if you have received the email.

Summary

I explained how to automate email sending. This time, one email was sent, but if you expand it, you can send multiple emails at once. If you send similar emails every time in your daily work, please refer to it.

Recommended Posts

To automatically send an email with an attachment using the Gmail API in Python
Send an email to Spushi's address with python
Send an email with Excel attached in Python
Send using Python with Gmail
Output the report as PDF from DB with Python and automatically attach it to an email and send it
[Python] Send an email with outlook
[Python] Create API to send Gmail
Send email via gmail with Python 3.4.3.
[Python] Send an email from gmail with two-step verification set
An easy way to hit the Amazon Product API in Python
Try using the Wunderlist API in Python
HTML email with image to send with python
[September 2020 version] Explains the procedure to use Gmail API with Python
Send email to multiple recipients in Python (Python 3)
Tweet using the Twitter API in Python
Send an email with Amazon SES + Python
Regularly upload files to Google Drive using the Google Drive API in Python
How to send a request to the DMM (FANZA) API with python
Create an application that just searches using the Google Custom Search API with Python 3.3.1 in Bottle
I tried to make it possible to automatically send an email just by double-clicking the [Python] icon
What to do if you couldn't send an email to Yahoo with Python.
Try sending an email with the Gmail API Client Library for Java
Email attachments using your gmail account in python.
I want to email from Gmail using Python.
Try using the BitFlyer Ligntning API in Python
Try using the DropBox Core API in Python
Send email with Python
Send Gmail in Python
I tried to make it possible to automatically send an email just by double-clicking the [GAS / Python] icon
I want to send Gmail with Python, but I can't because of an error
Continue to retrieve tweets containing specific keywords using the Streaming API in Python
I tried to automatically send the literature of the new coronavirus to LINE with Python
Initial settings when using the foursquare API in python
Convert the image in .zip to PDF with Python
I tried to explain how to get the article content with MediaWiki API in an easy-to-understand manner with examples (Python 3)
Send Japanese email with Python3
Send email in Python (Outlook)
Upload as open data using CKAN API in Python & automatically link with Github Actions
Call the API with python3.
The first API to make with python Djnago REST framework
How to manipulate the DOM in an iframe with Selenium
Code to send an email based on the Excel email list
An introduction to the modern socket API to learn in C
Things to keep in mind when using Python with AtCoder
Things to keep in mind when using cgi with python.
Tweet Now Playing to Twitter using the Spotify API. [Python]
Try to decipher the garbled attachment file name with Python
How to log in to AtCoder with Python and submit automatically
[boto3] Send an email using SES
Getting the arXiv API in Python
Hit the Sesami API in Python
[Automation] Send Outlook email with Python
In the python command python points to python3.8
Hit the Etherpad-lite API with Python
Create Gmail in Python without API
Hit the web API in Python
Note: Send an email with Django
Access the Twitter API in Python
An alternative to `pause` in Python
How to know the internal structure of an object in Python
Create an alias for Route53 to CloudFront with the AWS API