How to use Gmail to send email in Python

1 Add "App password"

  1. Go to Google account "Security", navigate to "Signing in to Google" and click "App passwords".

  1. Then select a type, here we use "Mail" and custom the device name.

  1. Type device name as "airflow", or you can choose any other name.

  1. Then you will get the app password here, COPY it.

2 Turn on IMAP

Login to your email, click "Settings" icon at the right top, and go to "Forwarding and POP/IMap", Click "Enable IMAP".

3 Python code

import smtplib
import ssl
from email.message import EmailMessage

def send_email():
    msg = EmailMessage()
    port = 587
    host = "smtp.gmail.com"
    sender = "<you gmail email address>"
    password = "<app password>"

    msg['From'] = sender
    msg['To'] = ["<receiver1>", "<receiver2>"]
    msg['Subject'] = "Test email subject"
    msg.set_content("Test email content")

    with smtplib.SMTP_SSL(host, port, timeout=5) as server:
        server.login(sender, password)
        server.send_message(msg)

Every thing will work good.

Reference:

  1. Python: "subject" not shown when sending email using smtplib module

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *