On this fast tip, excerpted from Useful Python, Stuart reveals you the way you need to use Python to ship emails by way of Gmail. This may be helpful for sending standing reviews and summaries of actions, for instance.

When writing scripts for our personal use, it’s helpful to have the ability to ship emails from them. For instance, if we construct a script that’s run as a scheduled job regularly, having it e-mail a abstract report back to us after it’s run could be a good approach to examine that the script did what it was imagined to, and likewise to see what it discovered. One thing that recurrently downloads information from an HTTP API after which processes it could possibly e-mail us an outline of what it discovered, in order that we are able to go and skim its outcomes.

For particulars on establishing scheduled duties, see the Windows, macOS, or Linux cron documentation.

There are various programmatic e-mail providers, comparable to SendGrid, Mandrill, and Mailgun. These are helpful if we’re producing a whole lot of e-mail. They’ve official APIs and paid plans, and if we’re establishing a large-scale operation, it’s actually value wanting into signing as much as considered one of these providers and utilizing their Python libraries to ship e-mail. However for one thing small or private, this could look like a whole lot of effort, and there’s another if now we have a Gmail account (as many individuals do).

There’s an official Google Gmail Python API and module, nevertheless it’s fairly annoying to arrange and use. Python comes with the smtplib and email modules as a part of the built-in library, and these are completely able to sending e-mail by way of Gmail after a bit setup. We will even use them to ship e-mail from ourself to ourself. We will’t ship too many emails this fashion, although. If we wish to ship tens or a whole lot of emails to many various recipients, it’s greatest to analyze the programmatic e-mail providers talked about above. However as an e-mail notification after a scheduled job, utilizing Gmail from Python might be the best private resolution.

To make use of our Gmail account to ship e-mail this fashion, we first need to arrange an app password for our Python script to make use of. Go to the App passwords of your Google account, and below Choose app, select Mail, and below Choose gadget select Different (customized identify) and fill in a reputation (comparable to “My Python Script”). We’ll be proven a display screen that lists our new app password. Make an observation of this password someplace.

Gmail app password screen showing the newly generated app password

To ship an e-mail, we’ll use the smtplib module. First, we have to outline the content material of our e-mail. This half is our job. It’s a Python string, so we are able to substitute values in, use a templating language, or construct it up from a listing; no matter’s handy. Right here, we’ll use a easy instance:

email_text = f"""
Hello! That is the report from our script.

Now we have added 1 + 2 and gotten the reply {1+2}.

Bye!
"""

We’ll additionally outline two variables to carry our Gmail account particulars: the account identify (which is the a part of our Gmail tackle earlier than @gmail.com) and the app password we simply created:

GMAIL_USERNAME = "mygmailaccount12345"
GMAIL_APP_PASSWORD = "yxyloqscucpxdsxq"

Subsequent, we’ll create the message as an object utilizing the e-mail module. An e-mail can have many various properties, however the essential ones right here (along with the textual content of the physique) are To, From, and Topic. From shall be set to our Gmail tackle, which we’ve already outlined, and To needs to be a string containing the e-mail tackle the e-mail is being despatched to. This may be our personal tackle, and if the e-mail goes to multiple particular person, we have to separate the addresses by commas. We’ll outline these in a listing, as a result of we’ll want the record later:

recipients = ["[email protected]"]
msg = MIMEText(email_text)
msg["Subject"] = "E mail report: a easy sum"
msg["To"] = ", ".be a part of(recipients)
msg["From"] = f"{GMAIL_USERNAME}@gmail.com"

Lastly, we’ll use smtplib to hook up with Gmail’s mail server, log in with our offered particulars, and ship the e-mail. SMTP is the underlying protocol that’s used to ship e-mail. Once we ship an e-mail from our regular e-mail app, SMTP is how the app really does that. Right here, we’re doing it straight from our personal 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.stop()

Our e-mail ought to now be despatched. Bear in mind, after all, that that is an introduction, so we’ve completed no error dealing with or enter validation. As talked about, if we’re sending numerous e-mail, we should always think about using a devoted service, and we should always take into consideration the necessity to deal with errors, failures to ship, and the like. However sending one alert e-mail to ourself, for instance, might be completed usefully with easy code like this.

This fast tip is an excerpt from Useful Python, out there on Pylogix Premium and from e book retailers.