Quick Tip: Sending Email via Gmail with Python

Share this article

Quick Tip: Sending Email via Gmail with Python

In this quick tip, excerpted from Useful Python, Stuart shows you how you can use Python to send emails via Gmail. This can be useful for sending status reports and summaries of activities, for example.

When writing scripts for our own use, it’s useful to be able to send emails from them. For example, if we build a script that’s run as a scheduled task on a regular basis, having it email a summary report to us after it’s run can be a good way to check that the script did what it was supposed to, and also to see what it found. Something that regularly downloads data from an HTTP API and then processes it can email us a description of what it found, so that we can go and read its results.

For details on setting up scheduled tasks, see the Windows, macOS, or Linux cron documentation.

There are many programmatic email services, such as SendGrid, Mandrill, and Mailgun. These are useful if we’re generating a lot of email. They have official APIs and paid plans, and if we’re setting up a large-scale operation, it’s certainly worth looking into signing up to one of these services and using their Python libraries to send email. But for something small or personal, this can seem like a lot of effort, and there’s an alternative if we have a Gmail account (as many people do).

There’s an official Google Gmail Python API and module, but it’s quite annoying to set up and use. Python comes with the smtplib and email modules as part of the built-in library, and these are perfectly capable of sending email via Gmail after a little setup. We can even use them to send email from ourself to ourself. We can’t send too many emails this way, though. If we want to send tens or hundreds of emails to many different recipients, it’s best to investigate the programmatic email services mentioned above. But as an email notification after a scheduled task, using Gmail from Python can be the ideal personal solution.

To use our Gmail account to send email this way, we first have to set up an app password for our Python script to use. Go to the App passwords of your Google account, and under Select app, choose Mail, and under Select device choose Other (custom name) and fill in a name (such as “My Python Script”). We’ll be shown a screen that lists our new app password. Make a note of this password somewhere.

Gmail app password screen showing the newly generated app password

To send an email, we’ll use the smtplib module. First, we need to define the content of our email. This part is our job. It’s a Python string, so we can substitute values in, use a templating language, or build it up from a list; whatever’s convenient. Here, we’ll use a simple example:

email_text = f"""
Hi! This is the report from our script.

We have added 1 + 2 and gotten the answer {1+2}.

Bye!
"""

We’ll also define two variables to hold our Gmail account details: the account name (which is the part of our Gmail address before @gmail.com) and the app password we just created:

GMAIL_USERNAME = "mygmailaccount12345"
GMAIL_APP_PASSWORD = "yxyloqscucpxdsxq"

Next, we’ll create the message as an object using the email module. An email can have many different properties, but the important ones here (in addition to the text of the body) are To, From, and Subject. From will be set to our Gmail address, which we’ve already defined, and To should be a string containing the email address the email is being sent to. This can be our own address, and if the email is going to more than one person, we need to separate the addresses by commas. We’ll define these in a list, because we’ll need the list later:

recipients = ["sil@kryogenix.org"]
msg = MIMEText(email_text)
msg["Subject"] = "Email report: a simple sum"
msg["To"] = ", ".join(recipients)
msg["From"] = f"{GMAIL_USERNAME}@gmail.com"

Finally, we’ll use smtplib to connect to Gmail’s mail server, log in with our provided details, and send the email. SMTP is the underlying protocol that’s used to send email. When we send an email from our normal email app, SMTP is how the app actually does that. Here, we’re doing it directly from our own code:

smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.login(GMAIL_USERNAME, GMAIL_APP_PASSWORD)
smtp_server.sendmail(msg["From"], recipients, msg.as_string())
smtp_server.quit()

Our email should now be sent. Be aware, of course, that this is an introduction, so we’ve done no error handling or input validation. As mentioned, if we’re sending lots of email, we should consider using a dedicated service, and we should think about the need to handle errors, failures to send, and the like. But sending one alert email to ourself, for example, can be done usefully with simple code like this.

This quick tip is an excerpt from Useful Python, available on SitePoint Premium and from ebook retailers.

Frequently Asked Questions (FAQs) about Sending Email via Gmail with Python

How can I set up my Gmail account to allow sending emails via Python?

To send emails via Python, you need to enable “Less secure app access” in your Gmail account. Go to your Google Account > Security > Less secure app access, and turn it on. However, Google doesn’t recommend this due to potential security risks. An alternative is to use “App Passwords” which is a 16-digit passcode that gives less secure apps or devices permission to access your Google Account.

What Python libraries are required to send emails via Gmail?

The Python libraries required to send emails via Gmail are smtplib and email.mime. The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener. The email.mime module creates email messages.

How can I attach files to my email using Python?

To attach files to your email, you can use the email.mime module. First, create a MIMEMultipart object, then open the file in bytestream and set it as a MIMEBase object. Finally, add the MIMEBase object to the MIMEMultipart object.

Can I send emails to multiple recipients at once using Python?

Yes, you can send emails to multiple recipients at once. You just need to pass a list of email addresses to the sendmail method of your SMTP object.

How can I add a subject to my email using Python?

You can add a subject to your email by setting the ‘Subject’ field of your email header. For example, msg[‘Subject’] = ‘The subject of your email’.

How can I send HTML emails using Python?

To send HTML emails, you need to create a MIMEText object with the HTML content and the ‘html’ subtype, then attach it to your email message.

How can I add CC and BCC to my email using Python?

You can add CC and BCC to your email by setting the ‘Cc’ and ‘Bcc’ fields of your email header. However, note that the sendmail method only sends the email to the addresses specified in the ‘To’ field. To send the email to the CC and BCC addresses, you need to add them to the recipient list of the sendmail method.

How can I handle SMTP server connection errors in Python?

You can handle SMTP server connection errors by using a try-except block. If an SMTPServerDisconnected error is raised, you can catch it and handle it appropriately.

How can I send emails with non-ASCII characters using Python?

To send emails with non-ASCII characters, you need to encode your email message as UTF-8. You can do this by calling the encode method on your email message string.

How can I schedule emails to be sent at a specific time using Python?

To schedule emails, you can use a task scheduler such as cron on Unix-based systems or Task Scheduler on Windows. You would need to write a script that sends the email and then schedule that script to run at your desired time.

Stuart LangridgeStuart Langridge
View Author

Stuart is a consultant CTO, software architect, and developer to startups and small firms on strategy, custom development, and how to best work with the dev team. Code and writings are to be found at kryogenix.org and social networks; Stuart himself is mostly to be found playing D&D or looking for the best vodka Collins in town.

gmailpythonPython Quick Tips
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week