This time, I will write about how to automatically send an email with an attachment using Python and the Gmail API.
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()
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.
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.