Python Intermediate - Lesson 14 - Email Automation, Safely


Python Intermediate · Lesson 14

Email Automation, Safely

Python can prepare and send email through an SMTP server. In this lesson, you’ll build a plain-text message with the standard library, keep account credentials out of your code, and make sending an explicit choice.

By the end, you can: create an email message, read settings from environment variables, connect to an SMTP server using TLS, and preview a draft before choosing to send.
Email safety: practice with your own address or a consenting test recipient. Do not send unsolicited bulk email. Never publish a password, app password, or API key in a Blogger post, source file, or browser-side JavaScript. Use a protected secret store or environment settings, and follow your email provider's sending rules.

1. Build an email message

EmailMessage represents an email. Set the sender, recipient, subject, and body before handing the message to an SMTP connection.

from email.message import EmailMessage

message = EmailMessage()
message["From"] = "sender@example.com"
message["To"] = "learner@example.com"
message["Subject"] = "Your weekly study summary"
message.set_content(
    "You studied Python for 75 minutes this week."
)

print(message)

The addresses above are examples. In a real program, obtain the addresses from configuration or ask the user; do not put personal information into a public lesson post.

2. Read configuration from the environment

Environment variables let a program read settings without embedding their values in the source code. A missing setting should produce a clear error rather than a confusing failure later.

import os

smtp_host = os.environ.get("SMTP_HOST")
smtp_user = os.environ.get("SMTP_USER")
smtp_password = os.environ.get("SMTP_PASSWORD")

if not all([smtp_host, smtp_user, smtp_password]):
    raise RuntimeError("SMTP settings are incomplete.")

Set secrets through your operating system's protected environment settings or a secrets manager such as Replit Secrets. Do not paste secret values into source code, screenshots, public posts, or shared chat.

3. Send through SMTP with TLS

Many SMTP services support STARTTLS on a provider-configured port, commonly 587. Confirm the correct server, port, and authentication method with your provider. This example uses a TLS context and a connection timeout.

import os
import smtplib
import ssl
from email.message import EmailMessage

message = EmailMessage()
message["From"] = os.environ["MAIL_FROM"]
message["To"] = os.environ["MAIL_TO"]
message["Subject"] = "Python practice update"
message.set_content("Your script prepared this update.")

context = ssl.create_default_context()

with smtplib.SMTP(
    os.environ["SMTP_HOST"],
    int(os.environ.get("SMTP_PORT", "587")),
    timeout=20
) as server:
    server.ehlo()
    server.starttls(context=context)
    server.ehlo()
    server.login(
        os.environ["SMTP_USER"],
        os.environ["SMTP_PASSWORD"]
    )
    server.send_message(message)

The exact SMTP settings depend on the provider. Some accounts require an app-specific password or OAuth; do not weaken account security to make a script work. If the provider requires a different secure connection method, follow its current documentation.

4. Preview before sending

Email is an external action: a sent message reaches another person's mailbox. A safe workflow prepares a draft first and asks for a deliberate send choice.

from pathlib import Path

draft_path = Path("practice_email.eml")

if draft_path.exists():
    print("Choose a different draft filename.")
else:
    draft_path.write_text(message.as_string(), encoding="utf-8")
    print(f"Saved a preview draft to {draft_path}")

An .eml file can often be opened by a mail program for review. It is only a local draft; the example above does not send anything.

5. Handle delivery errors

Network problems, rejected logins, and provider policies can interrupt delivery. Catch expected SMTP and operating-system errors and report the result without exposing a password.

import smtplib

try:
    # Put the SMTP connection and send_message() call here.
    pass
except smtplib.SMTPAuthenticationError:
    print("The server rejected the sign-in. Check protected settings.")
except smtplib.SMTPException as error:
    print(f"The mail server reported a problem: {error}")
except OSError as error:
    print(f"Could not connect to the mail server: {error}")
Do not retry forever: repeated attempts can trigger provider limits or duplicate messages. Make retries deliberate and check whether a previous send succeeded before sending again.

Hands-on exercises

  1. Create an EmailMessage with a subject and two-line plain-text body. Print the message without sending it.
  2. Save the message to practice_email.eml, but stop if that file already exists. Do not connect to an SMTP server for this exercise.
Show Solution & Common Mistakes

Exercise 1 — one possible solution

from email.message import EmailMessage

message = EmailMessage()
message["From"] = "sender@example.com"
message["To"] = "learner@example.com"
message["Subject"] = "Practice reminder"
message.set_content(
    "Review functions for 20 minutes.\n"
    "Then take a short break."
)

print(message)

Exercise 2 — one possible solution

from pathlib import Path

draft_path = Path("practice_email.eml")
if draft_path.exists():
    print("Choose another filename so the draft is not replaced.")
else:
    draft_path.write_text(message.as_string(), encoding="utf-8")
    print(f"Draft saved to {draft_path}")

Common mistakes:

  • Putting the account password directly in the source code or public Blogger post.
  • Assuming every provider uses the same SMTP hostname, port, or authentication method.
  • Sending a message before checking its recipient, subject, and body.
  • Printing a password or secret as part of an error message.
  • Retrying a send automatically without checking whether the first attempt already delivered.

Quick quiz

Choose an answer, then select Check answer.

1. Where should an SMTP password be stored?

2. What is a useful way to preview an email without sending it?

3. What should you do before choosing SMTP host and port values?

Mini-project: Reviewed Study Summary Email

Create a tool that prepares a weekly study summary email. By default it saves a local draft. It sends only when the person running it passes --send and types an explicit confirmation.

Requirements:

  • Build a plain-text email using EmailMessage.
  • Read addresses and SMTP settings from environment variables.
  • Save a local .eml draft by default.
  • Send only with --send and an explicit typed confirmation.
  • Use TLS, a timeout, and clear error messages that do not reveal secrets.
  • Do not overwrite an existing local draft.

Hints: use argparse to define --send; test the default draft mode before configuring SMTP. The credential variable values are not part of this post—set them in a protected environment where the program runs.

Show Full Project Solution
import argparse
from email.message import EmailMessage
import os
from pathlib import Path
import smtplib
import ssl


SESSIONS = [
    ("Functions", 25),
    ("SQLite practice", 30),
    ("Web APIs", 20),
]


def build_message(sender, recipient):
    total_minutes = sum(minutes for _, minutes in SESSIONS)
    lines = [
        "Your study sessions this week:",
        "",
    ]
    lines.extend(
        f"- {topic}: {minutes} minutes"
        for topic, minutes in SESSIONS
    )
    lines.extend(["", f"Total: {total_minutes} minutes"])

    message = EmailMessage()
    message["From"] = sender
    message["To"] = recipient
    message["Subject"] = "Your weekly Python study summary"
    message.set_content("\n".join(lines))
    return message


def save_draft(message, path):
    if path.exists():
        print(f"Draft already exists: {path}. Choose another filename.")
        return False

    path.write_text(message.as_string(), encoding="utf-8")
    print(f"Draft saved to {path}. Review it before sending.")
    return True


def send_message(message):
    required = [
        "SMTP_HOST",
        "SMTP_USER",
        "SMTP_PASSWORD",
        "MAIL_FROM",
        "MAIL_TO",
    ]
    missing = [name for name in required if not os.environ.get(name)]
    if missing:
        print("Missing protected settings: " + ", ".join(missing))
        return False

    try:
        port = int(os.environ.get("SMTP_PORT", "587"))
    except ValueError:
        print("SMTP_PORT must be a number.")
        return False

    context = ssl.create_default_context()
    try:
        with smtplib.SMTP(
            os.environ["SMTP_HOST"],
            port,
            timeout=20
        ) as server:
            server.ehlo()
            server.starttls(context=context)
            server.ehlo()
            server.login(
                os.environ["SMTP_USER"],
                os.environ["SMTP_PASSWORD"]
            )
            server.send_message(message)
    except smtplib.SMTPAuthenticationError:
        print("The server rejected sign-in. Check the protected settings.")
        return False
    except (smtplib.SMTPException, OSError) as error:
        print(f"Email was not confirmed as sent: {error}")
        return False

    print("Email sent.")
    return True


def main():
    parser = argparse.ArgumentParser(
        description="Prepare a study summary email; sending requires --send."
    )
    parser.add_argument(
        "--send",
        action="store_true",
        help="Send after review and typed confirmation."
    )
    args = parser.parse_args()

    sender = os.environ.get("MAIL_FROM", "").strip()
    recipient = os.environ.get("MAIL_TO", "").strip()
    if not sender or not recipient:
        print("Set MAIL_FROM and MAIL_TO in the protected environment.")
        return

    message = build_message(sender, recipient)
    if not args.send:
        save_draft(message, Path("study_summary.eml"))
        print("Preview mode only; no email was sent.")
        return

    print(f"About to send to: {recipient}")
    print("Review the .eml draft first, then type SEND to continue.")
    if input("Type SEND to confirm: ").strip() != "SEND":
        print("Cancelled; no email was sent.")
        return

    send_message(message)


if __name__ == "__main__":
    main()

Start by setting MAIL_FROM and MAIL_TO in a protected environment, then run the script without --send to create and review a local draft. Configure the SMTP settings only in the runtime that needs to send. Sending requires the additional --send flag and typing SEND; a cancelled prompt does not attempt delivery.

Provider-specific SMTP access may require extra account setup or a different authentication method. This teaching example does not configure an email provider or send any message by itself.

Posts les plus consultés de ce blog

Python Programming Exercises with Solutions - Complete Beginner's Guide

Python Basics - Capstone - Study Sprint Tracker

Python Intermediate - Lesson 10 - Working with Excel Spreadsheets