Sending Emails with smtplib
Security note
Section titled “Security note”Don’t hardcode passwords.
Prefer:
- app passwords
- environment variables
- secret managers
Plain text email
Section titled “Plain text email”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")Visualize it
Section titled “Visualize it”Sending an email with smtplib follows a straightforward compose-connect-send sequence.
flowchart LR
A["Compose message (subject, body, attachments)"] --> B["Connect to SMTP server (TLS)"]
B --> C["Log in"]
C --> D["Send"]
D --> E["Close connection"]
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading