emails

1.1.1 · active · verified Sun Apr 12

The 'emails' library is a modern Python package designed for building, templating, transforming, signing, and sending emails. It provides a high-level API to compose HTML and plain-text messages, attach files, embed inline images, render templates, apply HTML transformations, sign with DKIM, and send through SMTP without manually constructing MIME trees. Currently at version 1.1.1, the library is actively maintained with regular releases addressing new features and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart example demonstrates how to create and send an HTML email using the `emails` library. It initializes an HTML email message with a subject, HTML body, and sender information. It then attempts to send the email via an SMTP server, retrieving SMTP credentials from environment variables for security. The example includes basic error handling for the `send` operation. For full functionality like HTML transformations or templating, remember to install the respective optional dependencies.

import emails
import os

# Configure SMTP details using environment variables for security
SMTP_HOST = os.environ.get('SMTP_HOST', 'smtp.example.com')
SMTP_PORT = int(os.environ.get('SMTP_PORT', 587))
SMTP_USER = os.environ.get('SMTP_USER', 'billing@example.com')
SMTP_PASSWORD = os.environ.get('SMTP_PASSWORD', 'your-app-password')

recipient_email = os.environ.get('RECIPIENT_EMAIL', 'customer@example.com')
sender_email = os.environ.get('SENDER_EMAIL', 'billing@example.com')
sender_name = os.environ.get('SENDER_NAME', 'Billing Dept.')

message = emails.html(
    subject="Your Receipt from Example Store",
    html="<p>Hello!</p><p>Your payment was successfully received for Order #12345.</p><p>Thank you for your business!</p>",
    mail_from=(sender_name, sender_email)
)

# Example of attaching a file (replace with a real file path if needed)
# with open("receipt.pdf", "rb") as f:
#     message.attach(filename="receipt.pdf", data=f.read())

try:
    response = message.send(
        to=recipient_email,
        smtp={
            "host": SMTP_HOST,
            "port": SMTP_PORT,
            "tls": True, # Use TLS for secure connection
            "user": SMTP_USER,
            "password": SMTP_PASSWORD,
        },
    )

    if response.status_code == 250:
        print("Email sent successfully!")
    else:
        print(f"Failed to send email. Status code: {response.status_code}, Message: {response.message}")
except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →