On this page
  1. smtplib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Sending an Email over STARTTLS (Port 587) or Implicit TLS (Port 465)
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

smtplib

Prev: site | Up: stdlib_module | Next: socket
Rel: email, json, mailbox, mimetypes, base64
Ref: docs.python.org — smtplib
Tags: #public #python3 #stdlib


Import

import smtplib

Overview

SMTP and ESMTP client (SMTP, SMTP_SSL) for transmitting email.message.EmailMessage objects (built with email) over TLS-encrypted mail relays. Always enforce TLS (SMTP_SSL or starttls(context=ssl.create_default_context())) and explicit timeouts.

Quick Start

from email.message import EmailMessage
import smtplib
import ssl

msg = EmailMessage()
msg["Subject"] = "Status"
msg["From"] = "noreply@example.org"
msg["To"] = "user@example.org"
msg.set_content("All checks passed.")

ctx = ssl.create_default_context()
assert hasattr(smtplib, "SMTP_SSL") and ctx.check_hostname is True

Implementation Walkthrough

1. Sending an Email over STARTTLS (Port 587) or Implicit TLS (Port 465)

from email.message import EmailMessage
import smtplib
import ssl

def send_mail(host: str, port: int, user: str, password: str, msg: EmailMessage) -> None:
    ctx = ssl.create_default_context()
    with smtplib.SMTP(host, port, timeout=15) as server:
        server.ehlo()
        server.starttls(context=ctx)
        server.ehlo()
        server.login(user, password)
        server.send_message(msg)

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes