Explain Codes LogoExplain Codes Logo

How to send an email with Gmail as provider using Python?

python
email
smtplib
gmail-api
Alex KataevbyAlex Kataev·Jan 7, 2025
TLDR

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:

import smtplib from email.message import EmailMessage # Create your message here message_imparting_wisdom = EmailMessage() message_imparting_wisdom['Subject'], message_imparting_wisdom['From'], message_imparting_wisdom['To'] = \ 'Your Subject', '[email protected]', '[email protected]' message_imparting_wisdom.set_content('Free energy is a scam!') # Time to spread the wisdom with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp_no_place_like_home: smtp_no_place_like_home.login('[email protected]', 'app_password') smtp_no_place_like_home.send_message(message_imparting_wisdom)

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:

try: # Just trying to send email here, nothing else 😅 except Exception as e: print(f'Oopsie daisy! Email flopped: {e}') finally: # Don't forget to clean after yourself! server.quit()

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:

recipients = ['[email protected]', '[email protected]'] msg['To'] = ', '.join(recipients)

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