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