Sending Emails with Python

There are a few ways to send emails with python, but I wanted to find a way that was quick to implement, free, secure, with good delivery rates and could be used by a test application and a production application alike. What follows is how to set up sending email with python, utilising a gmail email account.

Step 1: Set up a Shiny New Gmail/Google Account

It is recommended to use a fresh account here. You don’t want to be doing development against your ‘real’ everyday account.

  1. Create new google/gmail account

Step 2: Create a Project in the Google API Console

You may be wondering, hang on, I just want to send an email. Why all this fuss? Well, bear with me, because this bit is required in order to authenticate securely to your email account for sending email.

  1. Go to the Google API Console and make sure you’re signed in as your new user
  2. Click on ‘New Project’
  3. Choose a project name and click ‘Create’
  4. Once created, select your project from the dropdown on the blue bar at the top
  5. Select ‘OAuth consent screen’ from the left-hand menu
  6. Select ‘External’ and click ‘Create’
  7. Fill in an app name, and use your new email address for the ‘support email’ and ‘Developer contact information’ email. You can leave the rest of the fields blank
  8. Click ‘Save and Continue’
  9. On the ‘Scopes’ screen, don’t change anything and click ‘Save and Continue’
  10. On the ‘Test Users’ screen, click ‘Add Users’ and enter the newly created email address into the box. Click ‘Add’. Then click ‘Save and Continue’

Step 3: Create OAuth Credentials in the Google API Console

This is the reason we created a project, so we could get OAuth credentials for sending email.

  1. Go to the Google API Console and make sure you’re signed in as your new user
  2. Select your project from the dropdown on the blue bar at the top
  3. Click on ‘Credentials’ on the left hand side
  4. Click ‘Create Credentials’ at the top
  5. Select ‘OAuth Client ID’ from the dropdown menu
  6. From the dropdown for ‘Application type’, select ‘Desktop app’. (This assumes you will be, at least initially, running your code to send emails from your desktop machine, or desktop-machine-hosted virtual machine. If this is not the case, select the appropriate application type)
  7. Enter a name for your auth client. I suggest using ‘Project Name client’, i.e. suffix the project name with ‘client’
  8. Click ‘Create’
  9. A pop-up will appear with your Client ID and Client Secret. Copy these and keep them somewhere safe. These are essentially your OAuth username/password to your new email account so you need to keep them secret.

Step 4: Create a Python Virtual Environment and Install yagmail

We are going to use the python package yagmail to send email. The yagmail package is a purpose-built package for sending email with Gmail, and makes working with OAuth and Gmail very simple (it does all the hard work for us).

  1. Go to your terminal and run the command for creating a new venv. This differs per operating system, but for linux/unix systems, the command would be:
    $ python -m venv .venv
  2. Active the venv (again, this is for linux/unix):
    $ . .venv/bin/activate
  3. Install yagmail:
    $ pip install yagmail

Step 5: Create the Email Sending Script

Use your favourite text editor or IDE to create a new python script. I’m going to call it send_email.py for the purposes of this example, but you can call it whatever you like. The contents of send_email.py will be as below. Be sure to replace the sender_email with your new gmail account and receiver_email with another email account that you have access to (so you can receive the test email).

import yagmail

sender_email = "yournewaccount@gmail.com"
receiver_email = "anotheraccount@somewhere.com"
body = """May the Code be with you!"""
try:
    yag = yagmail.SMTP(sender_email, oauth2_file="~/oauth2_creds.json")
    yag.send(
        to=receiver_email,
        subject="An email message from python",
        contents=body
    )
    print("Email sent")
except Exception as ex:
    print("An error occurred: " + str(ex))

Step 6: Initial Configuration Run

The eagle-eyed amongst you will have noticed that the script is referencing a file that we have not created yet: ~/oauth2_creds.json. This is because on this initial run of the code, yagmail will set up this file from some user input we give it. Now’s the time to get the OAuth Client ID and Secret ID handy.

  1. Run the script with:
    $ python send_email.py
  2. You should be presented with a prompt for your email address. Enter your newly created Gmail address
  3. Next, you’ll be prompted for your ‘google_client_id’. Paste the OAuth Client ID here
  4. Next, you’ll be prompted for your ‘google_client_secret’. Paste the OAuth Client Secret here. Note that the secret won’t be shown on the screen when you paste it
  5. You should now be presented with a URL for generating a Google refresh token. Copy this URL and navigate to it in your browser
  6. Choose the new google account (if prompted)
  7. You’ll get a warning that Google hasn’t verified this app. That’s OK, as your app is still in development. Click ‘Continue’
  8. Click ‘Allow’ to grant permission to your app
  9. On the ‘Confirm Your Choices’ screen, click ‘Allow’ again
  10. You should now be presented with a ‘sign in’ box, with a token. Copy the token and paste it into the prompt from your script on the terminal
  11. If all went well, the script continued to send the email, and you should see the output ‘Email sent’. Note that next time you run the script, it won’t prompt for all the credentials, as the ~/oauth2_creds.json should now have been created in your home directory.

Step 7: Second Run

You should be able to run the script now without entering the configuration details each time.

  1. From your terminal, run:
    $ python send_email.py
  2. This time, you should just get the output ‘Email sent’

Step 8: Check Your Email

Check the email account inbox for the email address you used as your receiver email. You should see two test email messages in there, with the subject: ‘An email message from python’.

Conclusion and Resources

That’s it, you’ve successfully sent an email using python! What’s more, it was secure, relatively quick to set up, free and sent using reputable mail relay servers, so unlikely to have ended up in the spam filter.

For further information on sending emails with python, check out the Real Python Guide on Sending Emails with Python, or check out the yagmail documentation. See you next time!