Quick Tip: Sending Email via Gmail with Python

    Stuart Langridge
    Share

    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.