Sooner or later almost every backend script needs to send an email. A nightly report, a password reset, an invoice, a “the import failed” alert at 2 a.m.
Python can do all of this with the standard library alone: smtplib to talk to the mail server and email.message.EmailMessage to build the message. No third-party packages needed.
Below is a complete script you can drop into a project, followed by a line-by-line look at the parts that usually go wrong.
What you need before you start
You need an SMTP server that will accept mail from you. Typical options:
| Provider | Host | Port | Notes |
|---|---|---|---|
| Gmail / Google Workspace | smtp.gmail.com | 587 | Needs 2-Step Verification plus an app password |
| Microsoft 365 | smtp.office365.com | 587 | Basic-auth SMTP is being retired; see the note below |
| Your hosting provider | varies | 587 or 465 | Check the control panel |
| Transactional services (SES, SendGrid, Mailgun, etc.) | varies | 587 | Best for high volume and deliverability |
Collect four values: host, port, username and password (or API key). We’ll read them from environment variables so they never end up in your code or Git history.
The complete script
import mimetypes
import os
import smtplib
import ssl
from email.message import EmailMessage
from pathlib import Path
SMTP_HOST = os.environ.get("SMTP_HOST", "smtp.gmail.com")
SMTP_PORT = int(os.environ.get("SMTP_PORT", "587"))
SMTP_USER = os.environ.get("SMTP_USER") # e.g. reports@yourcompany.com
SMTP_PASSWORD = os.environ.get("SMTP_PASSWORD") # app password, never hard-coded
USE_TLS = os.environ.get("SMTP_TLS", "1") == "1" # STARTTLS on port 587
def send_email(to, subject, text, html=None, attachments=()):
msg = EmailMessage()
msg["From"] = SMTP_USER or "noreply@example.com"
msg["To"] = ", ".join(to) if isinstance(to, (list, tuple)) else to
msg["Subject"] = subject
msg.set_content(text) # plain-text version
if html:
msg.add_alternative(html, subtype="html") # HTML version
for path in attachments:
path = Path(path)
ctype, _ = mimetypes.guess_type(path.name)
maintype, subtype = (ctype or "application/octet-stream").split("/", 1)
msg.add_attachment(path.read_bytes(), maintype=maintype,
subtype=subtype, filename=path.name)
context = ssl.create_default_context()
if SMTP_PORT == 465: # implicit TLS
server = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, context=context, timeout=30)
else:
server = smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=30)
with server:
if SMTP_PORT != 465 and USE_TLS:
server.starttls(context=context)
if SMTP_USER and SMTP_PASSWORD:
server.login(SMTP_USER, SMTP_PASSWORD)
server.send_message(msg)
if __name__ == "__main__":
send_email(
to=["accounts@example.com"],
subject="Daily sales report",
text="Hi team,\n\nPlease find today's sales report attached.\n",
html="<p>Hi team,</p><p>Please find <b>today's sales report</b> attached.</p>",
attachments=["sales_report.xlsx"],
)
print("Email sent")
Set the variables and run it:
# Windows PowerShell
$env:SMTP_HOST="smtp.gmail.com"
$env:SMTP_PORT="587"
$env:SMTP_USER="reports@yourcompany.com"
$env:SMTP_PASSWORD="your-app-password"
python send_mail.py
# Linux / macOS
export SMTP_HOST=smtp.gmail.com SMTP_PORT=587
export SMTP_USER=reports@yourcompany.com SMTP_PASSWORD='your-app-password'
python3 send_mail.py
How it works
Building the message
EmailMessage handles the messy MIME details for you.
msg.set_content(text)sets the plain-text body.msg.add_alternative(html, subtype="html")adds an HTML version of the same content. Email clients show the HTML part if they can and fall back to plain text if they can’t.
Always send both. Some corporate mail filters treat HTML-only messages as more suspicious, and plain text is what people see in notification previews and on smartwatches.
Attachments with the right MIME type
ctype, _ = mimetypes.guess_type(path.name)
maintype, subtype = (ctype or "application/octet-stream").split("/", 1)
This guesses the content type from the file extension, so a PDF is sent as application/pdf and an Excel file as the proper spreadsheet type. Many examples online send everything as application/octet-stream. That works, but some clients then won’t preview the file inline.
STARTTLS vs SSL: ports 587 and 465
This is the most common source of confusion:
- Port 587 (STARTTLS): the connection starts in plain text and is upgraded to encrypted with
server.starttls(). This is the modern default for most providers. - Port 465 (implicit TLS): the connection is encrypted from the first byte, so you use
smtplib.SMTP_SSLinstead.
The script picks the right one based on the port. If you use smtplib.SMTP on port 465, the connection will hang or fail with an unhelpful error, because the server is waiting for a TLS handshake that never starts.
ssl.create_default_context() makes sure the server’s certificate is actually checked. Don’t replace it with an unverified context to silence a certificate error. Fix the hostname or certificate issue instead.
Never hard-code the password
The credentials come from os.environ. On a server you can set them as system environment variables, in the Task Scheduler action, or through a secrets manager. If you prefer a file, use a .env file with python-dotenv and add it to .gitignore. Leaked SMTP passwords are routinely abused to send spam within hours of being pushed to a public repository.
Provider notes for 2027
Gmail and Google Workspace. Your normal Google password won’t work over SMTP. Turn on 2-Step Verification for the account, then create an app password and use that as SMTP_PASSWORD. Gmail also limits how many messages a regular account can send per day, so don’t use a personal Gmail account for bulk mail.
Microsoft 365 / Exchange Online. Microsoft is retiring Basic authentication (username and password) for SMTP AUTH client submission. Under its revised timeline, Basic auth is disabled by default from the end of December 2026, and Microsoft has said it will announce the final removal date in the second half of 2027. If your script logs in to smtp.office365.com with a password, plan to move to OAuth, an IP-based SMTP relay connector, or a transactional email service. Check Microsoft’s current guidance before you choose, because the dates have moved more than once.
Transactional services. If you send more than a few hundred emails a day, or the emails go to customers, use a service like Amazon SES, SendGrid, Mailgun or Postmark. They handle bounce processing, reputation and sending limits that a mailbox account was never designed for. Most still offer SMTP, so the script above works with only the credentials changed.
Errors you’re likely to hit
SMTPAuthenticationError: (535, ...) Wrong username or password, or the provider is blocking password login. For Gmail, use an app password. For Microsoft 365, check whether SMTP AUTH is enabled for the mailbox at all.
SMTPServerDisconnected or a long hang on connect Usually a port and TLS mismatch (see above), or a firewall blocking outbound port 587 or 465. Many cloud providers block outbound port 25 by default, so don’t use it for submission.
ssl.SSLCertVerificationError The host name you’re connecting to doesn’t match the server’s certificate. Use the exact host name your provider documents, not an IP address.
Email is sent but lands in spam That’s a domain reputation issue, not a Python issue. Make sure your sending domain has SPF, DKIM and DMARC records set up, and that the From address matches the account or domain you’re authenticating as.
UnicodeEncodeError in the subject or body EmailMessage handles UTF-8 properly. If you see this, you’re probably using the older MIMEText API with a manual charset. Switch to EmailMessage as shown.
Testing without sending real email
During development you don’t want test emails going to real inboxes. Run a local debugging SMTP server with the aiosmtpd package:
pip install aiosmtpd
python -m aiosmtpd -n -l localhost:8025
Then point the script at it:
SMTP_HOST=localhost SMTP_PORT=8025 SMTP_TLS=0 python3 send_mail.py
The full message, including headers and attachment encoding, is printed in the server’s terminal instead of being delivered. It’s a quick way to check that the HTML and attachments look right.
Putting it to work
Once send_email() works, it plugs into almost anything:
- Attach the PDF from our ReportLab invoice guide and email it to the customer.
- Send the Excel report from a Task Scheduler job every morning.
- Wrap your main script in
try/exceptand send yourself the traceback when something fails.
Quick checklist
- ☐ Credentials in environment variables, not in code
- ☐ Port 587 with STARTTLS, or port 465 with
SMTP_SSL - ☐ Both plain-text and HTML parts
- ☐ Attachments sent with a real MIME type
- ☐ SPF, DKIM and DMARC set up for the sending domain
- ☐ A transactional service for customer-facing or high-volume mail
- ☐ Microsoft 365 users: a plan to move off Basic auth SMTP
Leave a Comment