Email Module
Django-CFG’s Email Module provides an auto-configuring email service that reads settings from your DjangoConfig instance. All emails are sent in background threads so they never block request handling. Errors are automatically reported to Telegram if that module is configured.
Features
- Auto-configuration — reads
EmailConfigfromDjangoConfigwithout manual parameter passing - Background sending — all methods dispatch to a daemon thread and return immediately
- Template support — renders
.htmland.txtDjango templates with auto-injected context variables - HTML emails — automatic plain-text fallback derived from the HTML, with entities correctly decoded
- Database-backed content — per-locale letter copy (
EmailContent) with admin editing and a full send log (EmailLog) - Attachment support — send files with any email type via
EmailMultiAlternatives - Admin notifications — send to all addresses from
config.admin_emailsor DjangoADMINSsetting - Multi-channel alerts — single call sends to both email and Telegram simultaneously
- Telegram fallback — SMTP errors are forwarded to Telegram for visibility
Quick Start
Simple Text Email
from django_cfg import send_email
send_email(
subject="Hello World",
message="This is a test email.",
recipient_list=["[email protected]"],
)HTML Email
from django_cfg.modules.django_email import DjangoEmailService
email = DjangoEmailService()
email.send_html(
subject="Welcome!",
html_message="<h1>Welcome</h1><p>Thanks for joining us.</p>",
recipient_list=["[email protected]"],
)When no plain-text alternative is supplied, one is derived from the HTML via strip_tags followed by unescaping — so an apostrophe rendered as ' by template autoescaping shows up as ' in the text/plain part, not as a literal entity. The same unescaping is applied when a project supplies its own .txt template, so hand-written .txt templates render correctly too.
Template-Based Email
Templates are resolved by appending .html and .txt to the template_name.
email = DjangoEmailService()
email.send_template(
subject="Order Shipped",
template_name="emails/order_shipped",
context={
"user_name": "John Doe",
"order_id": "12345",
"tracking_url": "https://track.example.com/12345",
},
recipient_list=["[email protected]"],
)The following context variables are injected automatically if not present in context:
| Variable | Source |
|---|---|
project_name | config.project_name (deployment name) |
site_name | Site.name — the name the templates read |
site_url | Site.site_url |
support_email | Site.support_email — templates print it only when set |
logo_url | Site.logo_url — templates print it only when set |
site | the resolved Site object |
subscribe_url | EmailConfig.subscribe_url (or EMAIL_SUBSCRIBE_URL) — absent unless configured |
Your own context keys win over these. The values come from the site the mail is for.
Sending for a site
send_html and send_template take site=: a Site, a site key, or None for the default site.
service.send_template(
subject="Welcome!",
template_name="emails/welcome",
context={"user_name": "Jane Doe"},
recipient_list=["[email protected]"],
site="acme",
)The site decides the template context, the tracking base (Site.api_url), the From header and Reply-To. There is one sending address for all sites: Site.from_email, else EmailConfig.default_from, else Django DEFAULT_FROM_EMAIL. Each site brings its own display name (from_name, default Site.name), so Acme <[email protected]> and Beta <[email protected]> share one authenticated mailbox. Reply-To is Site.support_email, else EmailConfig.reply_to.
When subscribe_url is present, the shared base template renders a “P.S. Want {site_name} product updates? One click — subscribe” footer in every system email. See Configuration Reference.
Email with Attachments
email = DjangoEmailService()
email.send_with_attachments(
subject="Your Invoice",
recipient_list=["[email protected]"],
html_message="<p>Please find your invoice attached.</p>",
attachments=[
("invoice.pdf", pdf_bytes, "application/pdf"),
],
)Admin Notifications
from django_cfg import send_admin_email, send_admin_notification
# Email only — sent to all addresses in config.admin_emails
send_admin_email(
subject="[Alert] Database Backup Failed",
message='Backup for "default" database failed at 2025-01-15 02:00',
)
# Email + Telegram simultaneously
send_admin_notification(
subject="Database Backup Completed",
message='Backup "default_20250115_020000.sql.gz" created successfully',
)Configuration
from django_cfg import DjangoConfig
from django_cfg.models.services.email import EmailConfig
class MyConfig(DjangoConfig):
email = EmailConfig(
backend="smtp",
host="smtp.gmail.com",
port=587,
username="[email protected]",
password="${EMAIL_PASSWORD}",
use_tls=True,
default_from="[email protected]",
)
admin_emails = ["[email protected]", "[email protected]"]See Configuration Reference for all EmailConfig fields and provider examples. On Django 6.1+ the config is emitted as MAILERS, on 5.2 as EMAIL_*; on 6.1 remove any EMAIL_BACKEND from your own settings (Django 5.2 and 6.1).
Public API
Convenience Functions
from django_cfg import send_email, send_admin_email, send_admin_notification, get_admin_emails| Function | Description |
|---|---|
send_email(subject, message, recipient_list, ...) | Send a plain text email |
send_admin_email(subject, message, ...) | Send to all admin addresses |
send_admin_notification(subject, message, ...) | Send to admins via email and/or Telegram |
get_admin_emails() | Return list of configured admin email addresses |
DjangoEmailService
from django_cfg.modules.django_email import DjangoEmailService
service = DjangoEmailService()| Method | Description |
|---|---|
send_simple(subject, message, recipient_list, ..., headers=None) | Plain text email; headers={"X-Project-Key": "carapis"} adds message headers (the gateway backend passes them through) |
send_html(subject, html_message, recipient_list, ...) | HTML email with auto text fallback |
send_template(subject, template_name, context, recipient_list, ...) | Template-based email |
send_multipart(subject, recipient_list, html_content, ...) | Email with attachments |
send_with_attachments(subject, recipient_list, attachments, ...) | Universal attachment method |
send_template_with_tracking(subject, template_name, context, ..., email_log_id) | Template email with open/click tracking pixels |
is_configured() | Returns True if email_config.host is set |
get_backend_info() | Returns dict with current backend, host, port, TLS settings (read from MAILERS or EMAIL_*) |
Admin Email Resolution
get_admin_emails() resolves addresses in priority order:
config.admin_emails(list onDjangoConfig)- Django
ADMINSsetting ((name, email)pairs, or address strings as on Django 6.0+) - Empty list (no warning sent)
Error Handling
All SMTP errors are caught, logged, and silently forwarded to Telegram:
SMTPAuthenticationError— wrong credentialsSMTPDataError— quota or policy rejectionSMTPRecipientsRefused— recipient address rejectedSMTPSenderRefused— sender address rejectedsocket.timeout/TimeoutError— connection timeout
Use fail_silently=False to re-raise the exception after logging:
# Raises on any SMTP error
email.send_simple(
subject="Critical",
message="...",
recipient_list=["[email protected]"],
fail_silently=False,
)Management Commands
test_email
Send test emails for all built-in template types:
python manage.py test_email --email [email protected]
python manage.py test_email --email [email protected] --type otp
python manage.py test_email --email [email protected] --type all| Option | Default | Description |
|---|---|---|
--email | required | Recipient address (no default) |
--type | all | Template to send: all, base, otp, welcome, login_alert |
Built-in templates tested:
| Key | Template | Subject |
|---|---|---|
base | emails/base_email | General notification |
otp | emails/otp_email | OTP authentication code |
welcome | emails/welcome_email | New account welcome |
login_alert | emails/login_alert_email | Security login alert |
load_email_content
Loads per-locale letter copy into the database (EmailContent) so it can be edited in the admin without a deploy. See Content Management for the full flag reference.
See Also
- Content Management —
EmailContent,EmailLog, and theload_email_contentcommand - Configuration Reference — all
EmailConfigfields, provider setups - Telegram Module — Telegram notifications and combined alerts