Skip to content

Sending Emails with smtplib

Security note

Don’t hardcode passwords.

Prefer:

  • app passwords
  • environment variables
  • secret managers

Plain text email

smtp_plain.py
import os
import smtplib
from email.message import EmailMessage
 
SMTP_HOST = "smtp.gmail.com"
SMTP_PORT = 587
 
 
def send_email(to: str, subject: str, body: str):
    user = os.environ["SMTP_USER"]
    password = os.environ["SMTP_PASS"]
 
    msg = EmailMessage()
    msg["From"] = user
    msg["To"] = to
    msg["Subject"] = subject
    msg.set_content(body)
 
    with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as smtp:
        smtp.starttls()
        smtp.login(user, password)
        smtp.send_message(msg)
 
 
# send_email("to@example.com", "Hello", "Test")
smtp_plain.py
import os
import smtplib
from email.message import EmailMessage
 
SMTP_HOST = "smtp.gmail.com"
SMTP_PORT = 587
 
 
def send_email(to: str, subject: str, body: str):
    user = os.environ["SMTP_USER"]
    password = os.environ["SMTP_PASS"]
 
    msg = EmailMessage()
    msg["From"] = user
    msg["To"] = to
    msg["Subject"] = subject
    msg.set_content(body)
 
    with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as smtp:
        smtp.starttls()
        smtp.login(user, password)
        smtp.send_message(msg)
 
 
# send_email("to@example.com", "Hello", "Test")

πŸ§ͺ Try It Yourself

Exercise 1 – List Files with os.listdir

Exercise 2 – Join Paths with os.path.join

Exercise 3 – Write and Read a File

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did