Skip to Content
FeaturesModulesEmailEmail Module

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 EmailConfig from DjangoConfig without manual parameter passing
  • Background sending — all methods dispatch to a daemon thread and return immediately
  • Template support — renders .html and .txt Django 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_emails or Django ADMINS setting
  • 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 &#x27; 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:

VariableSource
project_nameconfig.project_name (deployment name)
site_nameSite.name — the name the templates read
site_urlSite.site_url
support_emailSite.support_email — templates print it only when set
logo_urlSite.logo_url — templates print it only when set
sitethe resolved Site object
subscribe_urlEmailConfig.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
FunctionDescription
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()
MethodDescription
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:

  1. config.admin_emails (list on DjangoConfig)
  2. Django ADMINS setting ((name, email) pairs, or address strings as on Django 6.0+)
  3. Empty list (no warning sent)

Error Handling

All SMTP errors are caught, logged, and silently forwarded to Telegram:

  • SMTPAuthenticationError — wrong credentials
  • SMTPDataError — quota or policy rejection
  • SMTPRecipientsRefused — recipient address rejected
  • SMTPSenderRefused — sender address rejected
  • socket.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
OptionDefaultDescription
--emailrequiredRecipient address (no default)
--typeallTemplate to send: all, base, otp, welcome, login_alert

Built-in templates tested:

KeyTemplateSubject
baseemails/base_emailGeneral notification
otpemails/otp_emailOTP authentication code
welcomeemails/welcome_emailNew account welcome
login_alertemails/login_alert_emailSecurity 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

Last updated on