Send emails with a Python SMTP script

Automating email is useful for alerts, reports and scheduled tasks. Python includes smtplib, a standard library module for connecting to SMTP servers and sending messages.

Connect to an SMTP server

import smtplib

conn = smtplib.SMTP('smtp.gmail.com', 587)
conn.ehlo()
conn.starttls()

Port 587 is commonly used for SMTP with STARTTLS.

Send a simple message

from email.message import EmailMessage
import smtplib

message = EmailMessage()
message["Subject"] = "Automated report"
message["From"] = "sender@example.com"
message["To"] = "recipient@example.com"
message.set_content("Hello, this message was sent from Python.")

with smtplib.SMTP("smtp.gmail.com", 587) as smtp:
    smtp.ehlo()
    smtp.starttls()
    smtp.login("sender@example.com", "app-password")
    smtp.send_message(message)

Security recommendations

Do not hardcode real passwords in scripts. Use environment variables, app passwords or a secret manager. If you use Gmail, enable an app password instead of using your main account password.

Common use cases

This approach works well for backup notifications, monitoring alerts, daily reports and internal automation.

Leave a Reply