Andromeda
Note

SMTP Protocol (Python)

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:
    1. Connect: smtplib.SMTP('smtp.provider.com', 587). Port 587 is for TLS (modern standard).
    2. Hello: smtpObj.ehlo() (Establishing the connection).
    3. Encrypt: smtpObj.starttls() (Secure connection).
    4. Auth: smtpObj.login(email, password).
    5. Send: smtpObj.sendmail(from, to, 'Subject: title\n\nBody'). Note: The body must start with the subject header and two newlines.
    6. Quit: smtpObj.quit().
  • Security: Use App Passwords for providers like Gmail when using smtplib directly, 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()

Connected Concepts