Definition
Simple Mail Transfer Protocol (SMTP) is the standard network protocol for sending emails. In Python, it is implemented via the built-in smtplib module.
Why It Matters
Understanding the SMTP protocol is critical for anyone building ‘automated messengers’; it provides the standardized framework for sending emails from code, enabling the remote monitoring and notification systems that keep modern software environments running smoothly.
Core Concepts
- The Send Lifecycle:
- Connect:
smtplib.SMTP('smtp.provider.com', 587). Port 587 is for TLS (modern standard). - Hello:
smtpObj.ehlo()(Establishing the connection). - Encrypt:
smtpObj.starttls()(Secure connection). - Auth:
smtpObj.login(email, password). - Send:
smtpObj.sendmail(from, to, 'Subject: title\n\nBody'). Note: The body must start with the subject header and two newlines. - Quit:
smtpObj.quit().
- Connect:
- Security: Use App Passwords for providers like Gmail when using
smtplibdirectly, as they block standard logins for less-secure apps.
import smtplib
# Connect to provider and send email
smtp_obj = smtplib.SMTP('smtp.example.com', 587)
smtp_obj.ehlo()
smtp_obj.starttls()
smtp_obj.login('my_email@example.com', 'my_password')
smtp_obj.sendmail('my_email@example.com', 'recipient@example.com',
'Subject: Hello\n\nDear recipient, this is a test email.')
smtp_obj.quit()