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")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
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 coffeeWas this page helpful?
Let us know how we did
