βοΈ Email & Messaging Automation
in Python
Build and send email with Python: EmailMessage, attachments, HTML, templates, smtplib with app passwords, scheduling, plus Telegram and Discord bots and retry logic.
What this lesson is about
Email is the oldest notification system on the internet and it is still the one every person and every service understands. A script that finishes a long job and tells you about it, a weekly report that lands in a manager's inbox, a reminder that goes out to forty members of a club: these are small programs with a large payoff, because the result arrives where people already look. Chat tools such as Telegram and Discord work in the same spirit, and they are often even easier to automate than email.
In this lesson I separate the problem into two halves that beginners usually mash together. The first half is building a message: headers, plain text, HTML, attachments, a template with names filled in. That half is pure Python and needs no network, so I can show you runnable examples and print what the message contains. The second half is delivering it: talking to a mail server with smtplib, or calling a chat service over HTTPS. Delivery needs credentials and a connection, so those examples are marked as run-on-your-computer, and I give you a fake sender that lets you test your own logic without sending anything real.
We go in this order: the anatomy of a message, attachments, HTML, templates, sending with SSL and app passwords, scheduling, etiquette and unsubscribe handling, the Telegram and Discord APIs, and finally a retry-safe sender you can run right here. Throughout I will keep one rule in front of you: test with a fake sender first, send to yourself second, and only then send to anyone else.
What you will learn
- βHow
email.message.EmailMessagerepresents headers, body and parts - βHow to attach files and check their sizes before sending
- βHow to write an HTML email with a plain-text fallback
- βHow to fill in personal details with
string.Templatefor a mail merge - βHow
smtplibandsslwork, and why passwords belong in environment variables - βHow to think about scheduling, duplicates and idempotent jobs
- βEmail etiquette: opt-outs, unsubscribe headers, pacing and honest subjects
- βHow the Telegram Bot API and Discord webhooks accept messages, with a testable retry sender
Why programmers should learn this
- β Notifications turn a script you have to babysit into one that tells you when it finishes or fails, which is the difference between a toy and a tool.
- β Understanding the message structure (headers, MIME parts) lets you debug the odd cases: attachments that arrive as garbage, accented names that break, HTML that shows as source.
- β Separating message building from sending makes your code testable, because the building half can be checked with plain assertions and no inbox.
- β Handling credentials correctly early (environment variables, app passwords) builds a habit that protects every later project that touches an API.
- β Chat webhooks and bot APIs follow the same pattern as most web services, so this lesson doubles as a gentle introduction to calling HTTP APIs with retries.
The anatomy of an email message
An email is simpler than it looks. It is a block of headers (From, To, Subject, Date and more), a blank line, and a body. When the body has several pieces, such as a plain-text version, an HTML version and two attachments, the message becomes a tree of MIME parts, each with its own content type. Python's standard library models all of this in email.message.EmailMessage, and it is the modern class to use. You may see older tutorials using MIMEText and MIMEMultipart; they still work, but EmailMessage needs far less ceremony.
The block below builds a message without sending anything. I set three headers with dictionary-style assignment, call set_content() for the body, and then read the message back. Notice that the To header can hold several recipients with display names, and that the default policy of EmailMessage parses them into address objects for you. That is much safer than slicing strings with split(','), which breaks the moment a display name contains a comma.
Building the message is also where you can catch mistakes cheaply. A header value that contains a newline is an injection risk: if a user-supplied subject could smuggle in Bcc: lines, your script could be used to send mail to strangers. The library refuses such values, and the second block shows that guard in action.
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "Glenn <glenn@example.com>"
msg["To"] = "Ana Cruz <ana@example.com>, ben@example.com"
msg["Subject"] = "Weekly report"
msg.set_content("Hi team,\n\nThe weekly report is ready.\n\nGlenn")
for name in ("From", "To", "Subject"):
print(name + ":", msg[name])
for address in msg["To"].addresses:
print("recipient:", address.display_name or "(no name)", "->", address.addr_spec)
print("type:", msg.get_content_type())
print("body:", repr(msg.get_content()))From: Glenn <glenn@example.com> To: Ana Cruz <ana@example.com>, ben@example.com Subject: Weekly report recipient: Ana Cruz -> ana@example.com recipient: (no name) -> ben@example.com type: text/plain body: 'Hi team,\n\nThe weekly report is ready.\n\nGlenn\n'
Line by line
- 1Import
EmailMessage, the class that holds one message. - 3-7Create an empty message, set three headers like dictionary keys, then set a plain-text body.
set_contentalso fills in the content-type headers for you. - 9-10Print the three headers we set; reading a header returns its text value.
- 12-13
msg["To"].addressesis a tuple of parsed address objects, so each recipient has adisplay_nameand anaddr_spec(the bare address). - 15-16Show the content type chosen automatically, and the body text.
reprmakes the newlines visible.
from email.message import EmailMessage
user_subject = "Invoice\nBcc: stranger@example.com"
msg = EmailMessage()
try:
msg["Subject"] = user_subject
except ValueError as error:
print("rejected:", error)
safe = " ".join(user_subject.split())
msg["Subject"] = safe
print("cleaned:", msg["Subject"])rejected: Header values may not contain linefeed or carriage return characters cleaned: Invoice Bcc: stranger@example.com
Line by line
- 3Pretend this subject came from a form or a file. The newline followed by
Bcc:is the attack. - 5-8Assigning it raises
ValueError, so the unsafe header never exists. - 10-12If you want to accept the text anyway, collapse all whitespace to single spaces first.
split()with no argument splits on any whitespace, including newlines.
Always set From, To and Subject. A message without a subject is more likely to look like junk to a recipient, and a missing From is rejected by many servers.
Attachments and size checks
Attaching a file means adding another MIME part with its own content type and a filename. With EmailMessage that is one call: add_attachment(data, maintype=..., subtype=..., filename=...). The data is bytes, so you read the file in binary mode (Path.read_bytes()), and the type comes from the file extension. The standard mimetypes module guesses it, and when it cannot, the safe fallback is application/octet-stream.
Two practical limits deserve attention. First, attachments are encoded for transport (base64 makes them about a third bigger), and many mail providers refuse messages above a size limit that you should look up for the services you use rather than assume. Second, a script that blindly attaches whatever is in a folder will eventually attach something it should not. I prefer to attach an explicit list of files and print their names and sizes before sending, so a human can glance at the log.
The example below creates the attachment contents in memory, so it runs anywhere, then reads the message back with iter_attachments(). This is exactly how you would write a test that proves your report script attached the right files. In real code replace the bytes with Path('report.csv').read_bytes().
import mimetypes
from email.message import EmailMessage
files = {
"report.csv": b"region,units\nnorth,120\nsouth,95\n",
"logo.png": bytes(range(64)),
"notes.unknownext": b"plain notes",
}
msg = EmailMessage()
msg["From"] = "reports@example.com"
msg["To"] = "boss@example.com"
msg["Subject"] = "Files attached"
msg.set_content("Please find the files attached.")
for name, data in files.items():
guessed, _ = mimetypes.guess_type(name)
maintype, subtype = (guessed or "application/octet-stream").split("/")
msg.add_attachment(data, maintype=maintype, subtype=subtype, filename=name)
total = 0
for part in msg.iter_attachments():
size = len(part.get_payload(decode=True))
total += size
print(f"{part.get_filename():18} {part.get_content_type():26} {size:4} bytes")
print("message type:", msg.get_content_type())
print("attachment bytes:", total)
LIMIT = 100
print("too big" if total > LIMIT else "within limit of", LIMIT)report.csv text/csv 32 bytes logo.png image/png 64 bytes notes.unknownext application/octet-stream 11 bytes message type: multipart/mixed attachment bytes: 107 too big 100
Line by line
- 1-2
mimetypesguesses a content type from a file name;EmailMessagebuilds the message. - 4-8Stand-in file contents as bytes. The last name has an unknown extension to test the fallback.
- 10-14A normal message with a plain-text body.
- 16-19For each file, guess its type (
guess_typereturns a pair; I keep the first). If the guess isNone, useapplication/octet-stream. Then splittext/csvinto main type and subtype and attach. - 21-25Walk only the attachment parts.
get_payload(decode=True)returns the original bytes, so the length is the real file size. The format specifiers align the columns. - 27-30Adding attachments turned the message into
multipart/mixed. Finally compare the total with a limit; in real code use the limit of your provider.
If you attach a file whose type you cannot guess, application/octet-stream is the honest answer. Do not label unknown data as text/plain, because mail clients may try to display it.
HTML emails with a plain-text fallback
Plain text is the baseline: it works everywhere, it is accessible, and spam filters treat it kindly. HTML lets you add a table, bold text or a link, and for newsletters or reports a little structure really does help. The standard way to offer both is a multipart/alternative message: you call set_content() with the plain text, then add_alternative(html, subtype="html"). The mail client chooses the richest version it can display, and clients that cannot show HTML fall back to the text.
Write the plain-text part properly, not as a lazy sentence saying that the message needs HTML. Anyone reading on a watch, a terminal or a screen reader will see only that version. Keep the HTML modest too: inline styles, simple tables, no scripts (mail clients strip them), and no heavy layout tricks. Mail clients render HTML far less consistently than browsers do, so every extra effect is another chance for something to look broken.
One more rule, which I consider non-negotiable: escape anything that comes from data. If a customer's name is A & B <Traders>, putting it straight into HTML will mangle the layout, and untrusted text in HTML is how markup injection happens. The standard html.escape() handles it. The example builds both versions, escapes the values, and then uses get_body() to read each version back, the same call a test would use.
import html
from email.message import EmailMessage
rows = [("North", 120), ("South & East", 95), ("<West>", 70)]
lines = [f"{name}: {units} units" for name, units in rows]
plain = "Sales report\n\n" + "\n".join(lines) + "\n"
cells = "".join(
f"<tr><td>{html.escape(name)}</td><td>{units}</td></tr>" for name, units in rows
)
page = f"<html><body><h2>Sales report</h2><table>{cells}</table></body></html>"
msg = EmailMessage()
msg["From"] = "reports@example.com"
msg["To"] = "boss@example.com"
msg["Subject"] = "Sales report"
msg.set_content(plain)
msg.add_alternative(page, subtype="html")
print("top-level type:", msg.get_content_type())
for part in msg.iter_parts():
print(" part:", part.get_content_type())
html_part = msg.get_body(preferencelist=("html",))
text_part = msg.get_body(preferencelist=("plain",))
print("html has escaped name:", "South & East" in html_part.get_content())
print("first text line:", text_part.get_content().splitlines()[0])top-level type: multipart/alternative part: text/plain part: text/html html has escaped name: True first text line: Sales report
Line by line
- 1-2
htmlprovidesescape;EmailMessageas before. - 4Sample data. Two names contain characters that are special in HTML.
- 6-7The plain-text version: one line per row. This is never optional in my own scripts.
- 9-12The HTML version.
html.escapeturns&and<into safe entities. Numbers need no escaping. - 14-19Create the message, set the text body first, then add the HTML as an alternative. Order matters: the last alternative is the preferred one.
- 21-23The top-level type is
multipart/alternative, with one child part per version. - 25-28
get_bodyfinds a specific version. I check that the ampersand was escaped and print the first text line.
For an image shown inside the HTML (a logo, for example), you attach it as a related part with a cid: reference. That needs a generated message id, so I have kept it as a static example in the later sending section rather than a runnable one.
Mail merge with string.Template
A mail merge is simply a template plus a table of rows. For short messages I like string.Template from the standard library. Its placeholders look like $name or ${name}, and, unlike f-strings, the template can live in a separate file or a configuration string that a non-programmer edits. It also does not evaluate code, which matters when the template text is not written by you.
There are two methods and the difference is worth knowing. substitute() raises KeyError if a placeholder has no value, which is exactly what you want in a mail merge: better to stop than to send a message that says Dear $name. safe_substitute() leaves unknown placeholders in place, which is handy for previews. I use substitute() inside the sending loop and treat a KeyError as a data problem to fix.
The merge below also does the unglamorous but essential checks: skip rows without an email address, strip stray spaces, and normalise the casing of the name. Building the list of messages first, and only then sending, gives you a dry run for free: print the list, read it, then press go.
from string import Template
from email.message import EmailMessage
template = Template(
"Hello $name,\n\n"
"Your next $club session is on $day at $time.\n"
"Reply to this message if you cannot come.\n\n"
"- Glenn\n"
)
members = [
{"name": " ana cruz ", "email": "ana@example.com", "day": "Friday", "time": "6 pm"},
{"name": "Ben Reyes", "email": "", "day": "Friday", "time": "6 pm"},
{"name": "carla", "email": "carla@example.com", "day": "Saturday"},
]
messages = []
for row in members:
email = row["email"].strip()
if not email:
print("skip (no address):", row["name"].strip())
continue
data = dict(row, name=row["name"].strip().title(), club="Python")
try:
body = template.substitute(data)
except KeyError as missing:
print("skip (missing value", missing, "):", email)
continue
msg = EmailMessage()
msg["From"] = "glenn@example.com"
msg["To"] = email
msg["Subject"] = f"Python club: {data['day']}"
msg.set_content(body)
messages.append(msg)
print("ready to send:", len(messages))
for msg in messages:
print("---", msg["To"], "|", msg["Subject"])
print(msg.get_content())skip (no address): Ben Reyes skip (missing value 'time' ): carla@example.com ready to send: 1 --- ana@example.com | Python club: Friday Hello Ana Cruz, Your next Python session is on Friday at 6 pm. Reply to this message if you cannot come. - Glenn
Line by line
- 1-9Define the template once.
$name,$club,$dayand$timeare the placeholders. - 11-15Three sample members: the first has messy spacing and casing, the second has no email, the third is missing a
timevalue. - 17-21Loop over rows and skip anyone without an address, telling the log why.
- 22Merge the row with a cleaned name and a constant
clubvalue.dict(row, name=...)copies the row with some keys replaced. - 23-27
substituteraisesKeyErrorfor a missing placeholder. I catch it, log it, and skip that row rather than sending a half-filled message. - 28-33Build a real message for each good row and collect them in a list. Nothing is sent.
- 35-38Print every message that would go out: this is the dry run.
Build all messages first, review the printed list, then send. A merge that goes wrong halfway is hard to take back, because you cannot unsend an email.
Sending with smtplib, SSL and app passwords
Delivery uses SMTP, and Python ships smtplib for it. You connect to your provider's SMTP server, secure the connection, log in, and hand over the message. There are two common ways to secure it. Port 465 starts encrypted from the first byte (SMTP_SSL). Port 587 starts plain and upgrades with starttls(). Which one your provider wants is written in their help pages; search for the SMTP settings of your provider rather than guessing. In both cases you pass an ssl.create_default_context() so that the server certificate is actually verified.
The credential rule is simple and I will repeat it: never type a password into your source file. Read it from an environment variable, or from a secrets store, and keep the script free of anything you would be embarrassed to publish. Many providers no longer accept your normal account password for scripts anyway, and instead offer an app password (a separate, revocable password created in your account security settings, often requiring two-step verification). Revoking an app password does not disturb your real login, which is exactly why it is the right tool here. The exact steps differ by provider and change over time, so follow their current documentation.
The first block is the real sending code, marked static because it needs a live server. The second block is the part you can run: the same logic written so that the connection is passed in. That one change, called dependency injection, lets you test everything except the network with a fake server class. In the fake I record each call, and the script prints them, so you can see the order: connect, upgrade, log in, send. The fake also checks that the password was read from the environment mapping and not hard-coded.
import os
import smtplib
import ssl
from email.message import EmailMessage
HOST = "smtp.example.com"
PORT = 465
USER = os.environ["SMTP_USER"]
PASSWORD = os.environ["SMTP_APP_PASSWORD"]
msg = EmailMessage()
msg["From"] = USER
msg["To"] = USER
msg["Subject"] = "Test from Python"
msg.set_content("If you can read this, SMTP works.")
context = ssl.create_default_context()
with smtplib.SMTP_SSL(HOST, PORT, context=context, timeout=30) as server:
server.login(USER, PASSWORD)
server.send_message(msg)
print("sent")
# Port 587 variant:
# with smtplib.SMTP(HOST, 587, timeout=30) as server:
# server.starttls(context=context)
# server.login(USER, PASSWORD)
# server.send_message(msg)Line by line
- 1-4Imports:
osfor environment variables,smtplibfor SMTP,sslfor certificate checking,EmailMessagefor the message. - 6-9Host and port come from your provider's documentation (the host here is a placeholder). User name and app password are read from the environment, so they are not in the file. A missing variable raises
KeyErrorimmediately, which is a clear failure. - 11-15Build a test message to yourself. Always test with your own address first.
- 17-21
create_default_context()gives secure defaults.SMTP_SSLopens an encrypted connection,loginauthenticates,send_messagesends. Thewithblock closes the connection even if something fails, andtimeoutstops a dead server from hanging your script forever. - 23-27Commented variant for port 587: connect plainly, call
starttlswith the same context, then log in.
import os
from email.message import EmailMessage
class FakeSMTP:
"""Stands in for smtplib.SMTP_SSL and records what happens."""
log = []
def __init__(self, host, port, **kwargs):
FakeSMTP.log.append(f"connect {host}:{port}")
def __enter__(self):
return self
def __exit__(self, *exc):
FakeSMTP.log.append("close")
return False
def login(self, user, password):
FakeSMTP.log.append(f"login {user} (password length {len(password)})")
def send_message(self, msg):
FakeSMTP.log.append(f"send to {msg['To']}")
def send_all(messages, env, connect):
user = env["SMTP_USER"]
password = env["SMTP_APP_PASSWORD"]
with connect("smtp.example.com", 465) as server:
server.login(user, password)
for msg in messages:
server.send_message(msg)
return len(messages)
def make(to):
msg = EmailMessage()
msg["From"] = "me@example.com"
msg["To"] = to
msg["Subject"] = "Hello"
msg.set_content("Hi")
return msg
fake_env = {"SMTP_USER": "me@example.com", "SMTP_APP_PASSWORD": "not-a-real-password"}
count = send_all([make("a@example.com"), make("b@example.com")], fake_env, FakeSMTP)
print("sent:", count)
for line in FakeSMTP.log:
print(" ", line)
try:
send_all([], {}, FakeSMTP)
except KeyError as missing:
print("missing setting:", missing)sent: 2 connect smtp.example.com:465 login me@example.com (password length 19) send to a@example.com send to b@example.com close missing setting: 'SMTP_USER'
Line by line
- 1-2
osis imported only because the real script reads the environment; the test passes a plain dictionary instead. - 5-22
FakeSMTPhas the same methods as the real client (login,send_message, and thewithprotocol) but only appends strings to a list. Nothing touches a network. - 25-32
send_allis the real logic. It receives the settings (env) and the way to connect (connect) as arguments, so tests can supply fakes and production code suppliessmtplib.SMTP_SSL. - 35-41A helper that builds a small message, as in earlier sections.
- 44-48Run the logic with fake settings and the fake server, then print the recorded call order.
- 50-53Prove the failure path: with empty settings the function stops with a
KeyErrorbefore connecting to anything.
Never commit passwords, even in a private repository. If one slips into a commit, revoke it at once and create a new one; deleting the file later does not remove it from history.
Scheduling: when should the script run?
A script that you start by hand is only half automation. The other half is when. You have three honest options. Let the operating system run it (cron on Linux and macOS, Task Scheduler on Windows), let a hosted scheduler run it (for example a scheduled workflow in a code-hosting service), or keep a Python process alive that sleeps and wakes up. The first two are more robust, because the operating system restarts jobs after a reboot, while a long-running script dies with the terminal that started it.
Whatever you choose, design the job to be idempotent: running it twice must not do harm. Schedulers retry, laptops wake up late, and you will run the script by hand while testing. If the weekly report script is run twice, nobody should get two reports. The usual trick is a record of what has already been sent, keyed by something stable such as the recipient plus the date. The block below computes the next run time and demonstrates a sent-log that blocks duplicates.
Time zones deserve a sentence of caution. A schedule that says 09:00 means 09:00 somewhere, and daylight saving changes can make a naive local time skip or repeat. For anything where this matters, store and compare times in UTC and convert only for display. The runnable example uses fixed dates so that its output never changes, and I show the cron line in a separate static block.
from datetime import datetime, timedelta
def next_weekday_run(now, weekday, hour, minute=0):
"""Next datetime on `weekday` (Monday=0) at hour:minute, strictly after now."""
days_ahead = (weekday - now.weekday()) % 7
candidate = (now + timedelta(days=days_ahead)).replace(
hour=hour, minute=minute, second=0, microsecond=0
)
if candidate <= now:
candidate += timedelta(days=7)
return candidate
now = datetime(2026, 12, 2, 10, 30) # a Wednesday
print("now: ", now.strftime("%a %Y-%m-%d %H:%M"))
for label, weekday in (("Friday", 4), ("Wednesday", 2), ("Monday", 0)):
run = next_weekday_run(now, weekday, 9)
print(f"next {label:9}", run.strftime("%a %Y-%m-%d %H:%M"))
sent_log = set()
def send_once(recipient, day):
key = (recipient, day.isoformat())
if key in sent_log:
return "skipped (already sent)"
sent_log.add(key)
return "sent"
today = now.date()
print(send_once("ana@example.com", today))
print(send_once("ana@example.com", today))
print(send_once("ben@example.com", today))now: Wed 2026-12-02 10:30 next Friday Fri 2026-12-04 09:00 next Wednesday Wed 2026-12-09 09:00 next Monday Mon 2026-12-07 09:00 sent skipped (already sent) sent
Line by line
- 1Only
datetimeandtimedeltaare needed. - 3-10Find the next given weekday at a given time.
(weekday - now.weekday()) % 7is the number of days ahead (0 if it is today). If the resulting time has already passed today, move a week forward. - 12-16A fixed
now(a Wednesday) makes the output repeatable. Try the next Friday, Wednesday and Monday at 09:00; Wednesday 09:00 has passed, so it jumps a week. - 18-25A set of
(recipient, date)keys.send_oncereturns early when the key exists, so a second run on the same day does nothing. - 27-30Same recipient twice, then a new one. Only repeats are skipped. In real code you would store this log in a file or database so it survives restarts.
# crontab -e (Linux / macOS) # minute hour day-of-month month day-of-week command 0 9 * * 5 cd /home/you/reports && /usr/bin/python3 send_report.py >> report.log 2>&1 # Windows (Task Scheduler) from a terminal, every Friday at 09:00: # schtasks /Create /SC WEEKLY /D FRI /ST 09:00 /TN "WeeklyReport" /TR "python C:\reports\send_report.py"
Line by line
- 1-3The five fields are minute, hour, day of month, month, day of week.
0 9 * * 5means 09:00 every Friday. The command changes into the folder first, uses the full path to Python, and appends output and errors to a log file so you can see what happened later. - 5-6A Windows equivalent with
schtasks, shown as a comment. Adjust the paths to your own machine.
Cron runs with a minimal environment: use full paths, and set secrets the way your platform recommends, because the variables from your interactive shell are not there.
Etiquette, consent and unsubscribe
Everything so far could be used to send unwanted mail, so let me be direct about the ethics, because they are also the practical rules that keep your messages delivered. Send to people who expect to hear from you: your own club, your own customers, colleagues who asked for the report. Do not scrape addresses, and do not buy lists. Laws about bulk and marketing email differ from country to country, so check the rules that apply to you and your recipients before sending anything promotional. This page is not legal advice.
The practical habits are these. Use an honest subject that says what is inside. Identify yourself. Give every recipient of a recurring message an easy way to stop it, and honour the request promptly. Keep a suppression list of addresses that opted out, and have your sending loop check it every time, because a list that is checked only when you remember will fail on the day you forget. Pace large sends: do not open a thousand connections a second. Providers apply limits that you should look up for your own account, and exceeding them can get the account suspended.
Mail software also understands a standard header, List-Unsubscribe, that lets the client show an unsubscribe button. You supply a mailto link or a web address in angle brackets. The block below adds the header, filters recipients against a suppression list, and works out how long a paced send would take. It is a small program, and it encodes most of what I think a careful sender needs.
from email.message import EmailMessage
recipients = ["ana@example.com", "Ben@Example.com", "carla@example.com", "dan@example.com"]
suppressed = {"ben@example.com", "dan@example.com"}
def normalise(address):
return address.strip().lower()
to_send = [a for a in recipients if normalise(a) not in suppressed]
skipped = [a for a in recipients if normalise(a) in suppressed]
print("sending to:", to_send)
print("opted out, skipped:", skipped)
def build(address):
msg = EmailMessage()
msg["From"] = "Python Club <club@example.com>"
msg["To"] = address
msg["Subject"] = "Club newsletter: December sessions"
msg["List-Unsubscribe"] = "<mailto:club@example.com?subject=unsubscribe>"
msg.set_content(
"Hello,\n\nHere are the December sessions.\n\n"
"You get this because you joined the club list.\n"
"To stop these messages reply with the word unsubscribe.\n"
)
return msg
first = build(to_send[0])
print("header:", first["List-Unsubscribe"])
PAUSE_SECONDS = 2
print("paced send of", len(to_send), "messages takes at least",
(len(to_send) - 1) * PAUSE_SECONDS, "seconds")sending to: ['ana@example.com', 'carla@example.com'] opted out, skipped: ['Ben@Example.com', 'dan@example.com'] header: <mailto:club@example.com?subject=unsubscribe> paced send of 2 messages takes at least 2 seconds
Line by line
- 3-4A recipient list and a suppression set. The set holds lowercase addresses for fast membership checks.
- 6-7Normalise before comparing: trim spaces and lowercase. Otherwise
Ben@Example.comwould slip past the check. - 9-12Split the list into people to mail and people who opted out, and print both so the log shows who was skipped and why.
- 14-25Build one message. The
List-Unsubscribeheader makes mail clients offer an unsubscribe action. The body states why the person receives it and how to stop. - 27-28Read the header back to confirm it is set.
- 30-32Pacing arithmetic: with a pause between messages, n messages need
(n - 1)pauses. Pick a pause that fits your provider's limits.
Notice that nothing here needs the network. The politeness rules live in ordinary code you can test, which is the best argument for building the message and the recipient list before any sending function runs.
Telegram bots and Discord webhooks
Chat services are often a better notification channel for yourself and your team than email. They arrive instantly, they do not need an SMTP account, and the APIs are small. Both Telegram and Discord accept an HTTPS request with a JSON body, so you call them with the requests library (see Requests and APIs for the basics). Because that library and the network are not available in the in-browser runner, the two examples in this section are static: copy them and run them on your computer.
For Telegram you create a bot by chatting with the official bot-creation bot inside the app, which hands you a token. The token is a password: treat it exactly like the SMTP app password and read it from an environment variable. You also need the numeric chat id of the conversation that should receive messages, which you can find by sending your bot a message and calling the getUpdates method. Sending is one call to sendMessage with chat_id and text. Telegram limits a single text message to 4096 characters.
For Discord you create a webhook in a channel's integration settings, which gives you a long secret URL. Posting JSON with a content field to that URL sends a message; a successful call returns status 204 with no body. A message may hold up to 2000 characters. Both services can answer 429 Too Many Requests and tell you how long to wait, which is why the next section builds a sender with retries. Keep the webhook URL out of your repository: anyone who has it can post to your channel.
import os
import requests
TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
CHAT_ID = os.environ["TELEGRAM_CHAT_ID"]
def send_telegram(text):
url = f"https://api.telegram.org/bot{TOKEN}/sendMessage"
response = requests.post(
url,
json={"chat_id": CHAT_ID, "text": text},
timeout=15,
)
response.raise_for_status()
return response.json()["ok"]
if __name__ == "__main__":
print(send_telegram("Backup finished without errors."))Line by line
- 1-2
osfor secrets,requestsfor the HTTPS call (install it with pip first). - 4-5Token and chat id come from environment variables, never from the file.
- 7-14The method name is part of the URL. We send a JSON body with the destination chat and the text, and set a timeout so a stalled connection cannot hang the script.
- 15-16
raise_for_status()turns 4xx and 5xx replies into exceptions, so failures are not silent. Telegram's JSON reply contains anokflag. - 18-19Only send when the file is run directly, so other scripts can import
send_telegram.
import os
import requests
WEBHOOK_URL = os.environ["DISCORD_WEBHOOK_URL"]
def send_discord(text, username="Build bot"):
response = requests.post(
WEBHOOK_URL,
json={"content": text[:2000], "username": username},
timeout=15,
)
if response.status_code == 429:
wait = response.json().get("retry_after", 1)
raise RuntimeError(f"rate limited, retry after {wait} seconds")
response.raise_for_status()
if __name__ == "__main__":
send_discord("Deployment finished.")Line by line
- 4The webhook URL is a secret, so it is read from the environment.
- 6-11POST a JSON body.
contentis the message, trimmed to Discord's 2000 character limit;usernameoverrides the display name for this message. - 12-14A 429 reply carries a
retry_aftervalue in its JSON body; here I report it. The next section turns this into automatic waiting. - 15Any other error status raises an exception. A successful webhook call returns 204 and no body.
A bot token or webhook URL gives anyone who holds it the power to post as your bot. If it ever leaks, regenerate it in the service's settings straight away.
A retry-safe sender you can test
Networks fail in boring ways: a timeout, a 502 from a busy server, a 429 asking you to slow down. A notification script that gives up on the first hiccup is not much of a notification script, and one that retries forever is worse. The pattern I use has three rules. Retry only errors that may go away (429 and 5xx), fail immediately on mistakes you must fix (a 401 for a bad token, a 400 for a bad request), and wait longer each time, preferring the server's own retry_after when it gives one. Put a cap on attempts so the script eventually reports failure.
The same section needs to deal with message size. Services limit a single message, so a long log has to be cut into chunks. Cutting at arbitrary character positions would split lines in half and make logs unreadable, so the splitter breaks on line boundaries and only hard-cuts a single line that is longer than the limit by itself.
To make this testable without a network I use a fake transport: a class with a post() method that returns scripted responses from a list, plus a fake sleep that records the waits instead of waiting. The real version would pass requests.post and time.sleep. Everything else is identical, so the logic you test here is the logic you ship.
class FakeResponse:
def __init__(self, status, retry_after=None):
self.status_code = status
self._retry_after = retry_after
def json(self):
return {"retry_after": self._retry_after} if self._retry_after else {}
class FakeTransport:
def __init__(self, statuses):
self.script = list(statuses)
self.calls = 0
def post(self, url, json=None, timeout=None):
self.calls += 1
status, retry_after = self.script.pop(0)
return FakeResponse(status, retry_after)
def split_message(text, limit):
chunks, current = [], ""
for line in text.splitlines():
while len(line) > limit:
if current:
chunks.append(current.rstrip("\n"))
current = ""
chunks.append(line[:limit])
line = line[limit:]
if len(current) + len(line) + 1 > limit and current:
chunks.append(current.rstrip("\n"))
current = ""
current += line + "\n"
if current:
chunks.append(current.rstrip("\n"))
return chunks
def send_with_retry(transport, sleep, url, text, max_attempts=4):
for attempt in range(1, max_attempts + 1):
response = transport.post(url, json={"content": text}, timeout=15)
code = response.status_code
if code in (200, 204):
return f"ok after {attempt} attempt(s)"
if code == 429 or code >= 500:
wait = response.json().get("retry_after") or 2 ** (attempt - 1)
if attempt == max_attempts:
break
print(f" attempt {attempt}: status {code}, waiting {wait}s")
sleep(wait)
continue
return f"failed permanently with status {code}"
return f"gave up after {max_attempts} attempts"
waits = []
log = "line one\nline two\n" + "x" * 25 + "\nlast line"
chunks = split_message(log, 20)
print("chunks:", chunks)
scenarios = {
"recovers": [(502, None), (429, 3), (204, None)],
"bad token": [(401, None)],
"always busy": [(503, None)] * 4,
}
for name, statuses in scenarios.items():
transport = FakeTransport(statuses)
print(name + ":")
print(" ", send_with_retry(transport, waits.append, "https://example.invalid/hook", "hi"))
print("recorded waits:", waits)chunks: ['line one\nline two', 'xxxxxxxxxxxxxxxxxxxx', 'xxxxx\nlast line'] recovers: attempt 1: status 502, waiting 1s attempt 2: status 429, waiting 3s ok after 3 attempt(s) bad token: failed permanently with status 401 always busy: attempt 1: status 503, waiting 1s attempt 2: status 503, waiting 2s attempt 3: status 503, waiting 4s gave up after 4 attempts recorded waits: [1, 3, 1, 2, 4]
Line by line
- 1-8A stand-in for an HTTP response: it has a status code and a JSON body that may contain
retry_after. - 11-19A stand-in for
requests. It is given a script of(status, retry_after)pairs and returns the next one on eachpostcall. - 22-37
split_messagebuilds chunks line by line. A line longer than the limit is hard-cut; otherwise a new chunk starts when adding the next line would exceed the limit. - 40-54The retry loop. Success statuses return. 429 and 5xx wait: the server's
retry_afterif present, else exponential backoff 1, 2, 4... seconds. Other statuses are permanent failures. The last attempt breaks out without waiting. - 57-60
waits.appendis passed as the sleep function, so nothing sleeps; we just record the delays. Then split a sample log with a 20 character limit. - 62-71Three scripted scenarios: a flaky server that recovers, a bad token that must not be retried, and a server that never recovers. Finally print every wait that was requested.
In production you would pass requests (its post has the same shape) and time.sleep into send_with_retry, and add random jitter to the waits so that many scripts do not all retry at the same instant. Keep max_attempts small: a notification that arrives an hour late is rarely useful.
Common mistakes
β Hard-coding the password or token
Putting credentials in the source file is the classic mistake, and it ends with a leaked secret in a repository. Read them from environment variables or a secrets store, use an app password where the provider offers one, and revoke anything that has been exposed.
β Sending before testing
A merge loop that goes wrong sends wrong mail to real people. Build the messages first, print them, send to your own address, and use a fake sender in tests. You cannot unsend an email.
β Pasting user text into headers or HTML unchecked
Newlines in headers allow injection, and raw text in HTML breaks the layout or worse. Let EmailMessage reject unsafe headers, clean values yourself, and run data through html.escape before it enters an HTML body.
β Retrying everything, or nothing
A script that never retries fails on every short outage, while one that retries a 401 forever just hammers the server. Retry 429 and 5xx with growing waits and a cap, and fail fast on errors you must fix yourself.
β Ignoring unsubscribe requests
Emailing someone who asked to stop is rude, can breach the law where you live, and damages your sender reputation. Keep a suppression list and check it in the sending loop, not by memory.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. Which class is the modern, recommended way to build a message in the standard library?
EmailMessage handles headers, bodies, alternatives and attachments with a small API. MIMEText and MIMEMultipart are the older style.Q2. How do you offer both a plain-text and an HTML version of one message?
Q3. Why use an app password and an environment variable?
Q4. What does string.Template.substitute() do when a placeholder has no value?
substitute raises KeyError, which stops a half-filled message from going out. safe_substitute is the one that leaves placeholders alone.Q5. Which HTTP statuses should a notification sender normally retry?
Q6. What is the main benefit of passing the SMTP connection into your send function?
Frequently asked questions
Can I send email from Python without an SMTP account?
+You need some account that is allowed to send: your mail provider's SMTP service, or a transactional email service with its own API. Python itself only speaks the protocol. Free personal accounts usually allow scripts when you create an app password, but each provider's rules and limits change, so read their current help pages.
Why does my email arrive in spam?
+Common causes are a sender domain without proper authentication records, misleading subjects, very little text with large images, and sending many near-identical messages quickly. For personal scripts sent through your real provider it is usually fine; for domains you own, ask your provider how to set up the authentication records they require.
What is the difference between port 465 and 587?
+Port 465 uses an encrypted connection from the very start (SMTP_SSL). Port 587 starts unencrypted and upgrades using starttls(). Both are safe when you pass a default SSL context and the server supports them; use whichever your provider documents.
Can I just use an f-string instead of string.Template?
+Yes, for templates that live in your code. string.Template earns its place when the text lives in a separate file or setting that other people edit, because it cannot execute code and has a clear error for missing values.
Is a Telegram bot or a Discord webhook better than email for alerts?
+For personal and small-team alerts they are often simpler: no SMTP setup, quick delivery, easy formatting. Email is better for formal records, attachments, and people who are not in your chat. Many scripts use chat for urgent alerts and email for reports.
Key takeaways
- βBuild messages with
EmailMessage: headers by assignment,set_contentfor text,add_alternativefor HTML,add_attachmentfor files. - βEscape data in HTML, reject newlines in headers, and always provide a plain-text version.
- βUse
string.Template.substitutefor mail merges so missing values stop the run, and review a printed dry run before sending. - βSend with
smtplibandssl.create_default_context(), read secrets from environment variables, and prefer app passwords. - βMake scheduled jobs idempotent, honour unsubscribe requests, and pace your sending.
- βFor Telegram and Discord, call the HTTPS APIs with timeouts, retry only 429 and 5xx with backoff, and test the logic with a fake transport.