Email Automation & Notifications
Send automated emails, reports, and notifications using smtplib and yagmail.
smtplib: The Standard Way
Python's built-in smtplib module lets you connect to an SMTP server and send messages.
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg.set_content("This is a test email from Python.")
msg['Subject'] = "Python Automation Alert"
msg['From'] = "pk@example.com"
msg['To'] = "user@example.com"
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login('user@gmail.com', 'app-password')
smtp.send_message(msg)
from email.message import EmailMessage
msg = EmailMessage()
msg.set_content("This is a test email from Python.")
msg['Subject'] = "Python Automation Alert"
msg['From'] = "pk@example.com"
msg['To'] = "user@example.com"
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login('user@gmail.com', 'app-password')
smtp.send_message(msg)
yagmail: The Easier Way
yagmail simplifies the process significantly, especially for Gmail.
import yagmail
yag = yagmail.SMTP('user@gmail.com', 'app-password')
yag.send(
to='user@example.com',
subject='Easy Email',
contents='Sent with just a few lines of code!',
attachments=['report.pdf']
)
yag = yagmail.SMTP('user@gmail.com', 'app-password')
yag.send(
to='user@example.com',
subject='Easy Email',
contents='Sent with just a few lines of code!',
attachments=['report.pdf']
)
Best Practices
- App Passwords: Never use your main account password. Generate a specific app password.
- Environment Variables: Store credentials in
.envfiles. - Rate Limits: Providers like Gmail have limits on how many emails you can send per day.
- HTML Content: Use HTML for professional-looking reports and notifications.
โ Practice (20 minutes)
- Set up a free mail trap account or use Gmail with an app password.
- Write a script that sends a daily "Status Report" email.
- Attach a CSV file to your email.
- Use an HTML template for the email body.