Email, messages, and notifications.
Build a message pipeline that is clear, authorised, and safe to retry.
Start here.
Sending a message is a side effect: the program reaches another person or service. An email has recipients, a subject, and a body. A transport such as SMTP or a provider API accepts the message for delivery, but acceptance does not prove the recipient has read it. Text messages and push notifications have similar stages and service-specific requirements. Code should distinguish composing a message from sending it.
Credentials authorize sending and must stay outside source files. Configuration supplies server addresses, sender identity, and limits. A message should be assembled from validated values, with recipients checked before the send call. If a loop sends many messages, a repeated run can produce duplicates unless the program records what it has already sent or uses an idempotency key supported by the provider.
The example in this chapter illustrates a provider or transport boundary; exact account settings depend on the service. Read a send result as evidence that the service accepted a request, then handle errors such as authentication failure, rate limits, and network interruption. For a reader, the key model is input data → message object → authenticated service call → recorded outcome. A preview and a clear recipient list make that outcome easier to understand.
Build the model.
Sending a message is a side effect: it reaches another person and may be impossible to recall. Build the recipient list and message body as data first, then review them before the sending step. A dry-run mode that prints the destination and a preview is especially useful while you are testing an automation.
Email, SMS, and push providers have different transports, but the same questions recur. Who is the recipient? What credentials allow this action? How will the provider report failure? How many times may the program retry? Does the message contain private data? Answer these questions before scheduling a script that can send many messages.
How it works.
Python's email.message.EmailMessage constructs a standards-aware email with headers and a body. smtplib sends it through an SMTP server, often with TLS and provider-specific authentication. Store credentials in environment variables or a secret store, not source code. Some providers require an API or app password rather than a normal account password; follow that provider's documentation.
A network call can time out after the provider accepted the message. Retrying blindly may send a duplicate. When a provider supports an idempotency key or message identifier, use it; otherwise record the intended send and result so your script can decide what to do on rerun. Rate limits and opt-in rules also matter when recipients are people, so test with your own address first.
Treat an API response as evidence, not proof of delivery. A successful request may only mean a provider queued the message. Store enough context to diagnose a failure without logging secret tokens or the full private message. Keep composition, transport, and logging in separate functions so each can be tested independently.
Read it line by line.
from email.message import EmailMessage
message = EmailMessage()
message['From'] = 'sender@example.com'
message['To'] = 'reader@example.com'
message['Subject'] = 'Your weekly summary'
message.set_content('Three tasks were completed this week.')
print(message['Subject'])EmailMessage creates a structured email. Header assignment identifies sender, recipient, and subject; set_content adds a plain-text body. This example only builds and prints a preview. Sending requires an SMTP connection or provider API, valid credentials, TLS, and explicit permission to contact the recipient.
See the rule again.
def preview(to, subject, body):
if '@' not in to:
raise ValueError('check recipient address')
return f'To: {to}\nSubject: {subject}\n\n{body}'
print(preview('me@example.com', 'Report', 'Ready.'))The function returns a reviewable string and rejects an obviously malformed address. This is only a basic check, not full email-address validation. A sending function can accept the same values after the preview is approved.
A mistake to avoid.
Do not place an API token in a tutorial file or commit. Do not retry every failed send indefinitely; some failures are permanent and an ambiguous timeout can produce duplicates.