How to send an email with Gmail as provider using Python?
The Python smtplib
library provides an SMTP client session that can be utilized to send an email via Gmail's SMTP server. Here's a quick rundown:
Assume [email protected]
and app_password
to be your Gmail email and app password respectively.
Securing your actions
Google recommends the use of App Passwords for accessing Gmail services through third-party apps for enhancing security. To create an app password, you'll need to enable 2-Step Verification first.
Facing an SMTPAuthenticationError
? This might mean you have to unlock the CAPTCHA for your account or you may prefer to follow the less secure approach of enabling access for "less secure apps" in your Google account settings.
When connecting with server.starttls()
use port 587 and make sure to call server.ehlo()
before and after server.starttls()
. If you hit a snag, use smtplib.SMTP_SSL
with port 465 as a safer bet.
Error handling and clean-up
It's a good practice to handle exceptions while sending emails:
The above snippet makes sure the server connection is gracefully shut down using server.quit()
.
When smtplib doesn't cut it — Use Gmail API
A Gmail API approach is more comprehensive and offers better security by leveraging OAuth2. The setup involves setting up a project in the Google Developers Console, enabling the Gmail API and getting your hands on those OAuth2 credentials.
Taking it further: Multiple recipients & HTML email content
Sending emails to multiple recipients involves tweaking 'To' field:
Mix things up by sending HTML content using MIME
subclasses. Attach these to your EmailMessage
object and voilà, you're sorted!
Be Patient
Config changes, especially security settings on Gmail can take a while to kick in. Don't sweat it!
If smtplib
isn't cutting it for you, consider using yagmail
, a Gmail-specific library that simplifies procedures.
References
Was this article helpful?