Skip to content

mobinyousefi-cs/Send-Emails-with-Python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Send Emails with Python (SMTP + Templates + Attachments)

A clean, production-ready Python package to send emails via SMTP with:

  • ✅ TLS/STARTTLS and environment-based configuration
  • ✅ Plain-text + HTML bodies for deliverability
  • ✅ Attachments and inline images (by Content-ID)
  • ✅ Jinja2 templates
  • ✅ Typer CLI and rich logging
  • ✅ src/ layout, tests, and examples

Author: Mobin Yousefi — MIT License


Quick Start

# 1) Clone & enter
git clone https://github.com/mobinyousefi-cs/email-sender.git
cd email-sender

# 2) Create a virtualenv (recommended)
python -m venv .venv && source .venv/bin/activate  # Windows: .venv\\Scripts\\activate

# 3) Install
pip install -e .

# 4) Configure
cp .env.example .env
# Edit .env with your SMTP settings (use an App Password for Gmail accounts)

# 5) Send an email via CLI
python -m email_sender.cli \
  "Test User <recipient@example.com>" \
  --subject "Hello from email-sender" \
  --template-html welcome.html.j2 \
  --template-text welcome.txt.j2 \
  --templates src/email_sender/templates

Programmatic Usage

from pathlib import Path
from email_sender.config import Settings
from email_sender.mailer import SMTPClient
from email_sender.models import EmailAddress, EmailContent, Attachment

settings = Settings.from_env()
client = SMTPClient(settings, template_dir=Path("src/email_sender/templates"))

html = client.render_template("welcome.html.j2")
text = client.render_template("welcome.txt.j2")
content = EmailContent(subject="Welcome!", text=text, html=html)

client.send(
    to=[EmailAddress("recipient@example.com", "User")],
    content=content,
    attachments=[Attachment(Path("/path/to/image.png"), inline_cid="hero-image")],
)

Configuration

Set environment variables or use .env (loaded via python-dotenv):

  • SMTP_HOST (e.g., smtp.gmail.com)
  • SMTP_PORT (e.g., 587)
  • SMTP_USERNAME, SMTP_PASSWORD (use app-specific passwords)
  • SMTP_FROM_NAME, SMTP_FROM_EMAIL
  • SMTP_USE_TLS (true/false)
  • SMTP_TIMEOUT_SECONDS
  • DEFAULT_REPLY_TO

Gmail Tip: For Gmail, enable 2‑step verification and create an App Password for SMTP.


Notes on SMTP Providers

  • Some providers rate-limit or block bulk emails. Pace with send_bulk(..., pace_seconds=0.5).
  • Always include a text part along with HTML for better deliverability.
  • Avoid spammy words and test with tools like Mail-Tester.

Development

pip install -e .[dev]
pytest -q
ruff check .

License

MIT © 2025 Mobin Yousefi

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published