Skillversitas

Sending Email

Python provides the smtplib module for sending email and the email module for formatting messages.

SMTP (Simple Mail Transfer Protocol) is the standard protocol for sending email over the internet. The smtplib module handles communication with the SMTP server, while the email module handles building the message structure — including headers (From, To, Subject), plain text or HTML body, and attachments. Together, they enable automating email sending from Python scripts without a browser or email client.

Modern email security requires encryption. The code example below uses SMTP_SSL, which encrypts the entire connection via SSL/TLS on port 465. Alternatively, SMTP with .starttls() can be used for port 587. Services like Gmail require an App Password when two-factor authentication is active — never store your password directly in code; use an environment variable or a separate configuration file.

Code Example

import smtplib
from email.mime.text import MIMEText

# Configuration
sender = "[email protected]"
recipient = "[email protected]"
password = "your_app_password"

# Create the message
msg = MIMEText("This is the email body from Python.")
msg["Subject"] = "Test Python Email"
msg["From"] = sender
msg["To"] = recipient

# Send via Gmail SMTP
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
    server.login(sender, password)
    server.send_message(msg)
    print("Email sent!")

Code Explanation

  • MIMEText("This is the email body from Python.") creates a message object with a plain text body. MIME allows adding multipart content such as HTML and attachments.
  • The Subject, From, and To attributes are set as email headers. Their values will appear in the recipient's inbox.
  • smtplib.SMTP_SSL("smtp.gmail.com", 465) opens an encrypted connection to the Gmail SMTP server. Port 465 is the standard port for SMTP SSL.
  • server.login(sender, password) authenticates to the SMTP server using the email credentials.
  • server.send_message(msg) sends the formatted message. This method automatically adds the Date and Message-ID headers if they don't exist.
  • Using with (context manager) ensures the connection is closed automatically after the code block finishes, even if an error occurs.

Everyday Example

An online store sends automatic notification emails using Python scripts. When a customer checks out, the system calls a function that uses smtplib to send an order confirmation email with product details and the total price. The same script is also used to send password reset emails, weekly newsletters, and daily sales reports to the store owner. All of this runs without manual intervention.

Summary

smtplib and email give Python the ability to send email programmatically. The server configuration — create message — send — close connection pattern is easy to learn and can be extended for attachments, HTML email, or bulk sending. Always use encrypted connections and store credentials securely.