Email Models
Backend selection
Django-CFG provides type-safe email configuration. The default backend is console; set backend="smtp" (or "gateway") and default_from for production.
Django-CFG provides EmailConfig model for type-safe email configuration with support for SMTP and Console backends.
EmailConfig
Type-safe email service configuration.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
backend | Literal["smtp", "console", "file", "memory", "dummy", "gateway"] | "console" | Email backend type |
host | str | "localhost" | SMTP server hostname |
port | int | 587 | SMTP server port (1-65535) |
username | str | None | None | SMTP username |
password | str | None | None | SMTP password |
use_tls | bool | True | Use TLS encryption |
use_ssl | bool | False | Use SSL encryption |
ssl_verify | bool | True | Verify SSL certificates (set False for self-signed certs in dev) |
default_from | str | None | None | The one sending address for every site. Required in production with smtp/gateway (startup error otherwise). |
default_from_name | str | None | None | Display name shown in the inbox (defaults to the project name) |
reply_to | str | None | None | Address that receives replies, when it differs from the sender |
file_path | str | "emails/" | Path for file-based email backend |
timeout | int | 30 | Email send timeout in seconds (1-300) |
gateway_url | str | None | None | Email gateway send endpoint (required for backend="gateway") |
gateway_secret | str | None | None | Shared secret sent to the gateway as a Bearer token (required for backend="gateway") |
subscribe_url | str | None | None | Newsletter subscribe URL for the system-email P.S. footer |
Methods
| Method | Returns | Description |
|---|---|---|
to_django_settings() | dict | Django email settings: MAILERS on Django 6.1+, EMAIL_* on 5.2 (see below) |
to_mailer() | dict | One MAILERS entry, {"BACKEND": ..., "OPTIONS": {...}} |
backend_path() | str | Dotted path of the backend class for backend |
backend_options() | dict | The backend’s constructor options under Django’s MAILERS names |
Django 5.2 and 6.1: EMAIL_* or MAILERS
Django 6.1 deprecates EMAIL_BACKEND and the other EMAIL_* connection settings
(removed in Django 2028) in favour of MAILERS, and refuses both at once. EmailConfig
emits what the running Django expects:
| Django | Generated settings |
|---|---|
| 5.2 | EMAIL_BACKEND, EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER, … (and EMAIL_GATEWAY_URL / EMAIL_GATEWAY_SECRET for the gateway) |
| 6.1+ | MAILERS = {"default": EmailConfig.to_mailer()} |
Both lines also get DEFAULT_FROM_EMAIL (when default_from is set) and
EMAIL_SUBSCRIBE_URL (when subscribe_url is set); those are not connection settings.
MAILERS["default"]["OPTIONS"] uses Django’s names: host, port, username,
password, use_tls, use_ssl, timeout for smtp; file_path for file;
gateway_url, gateway_secret, timeout for gateway. console, memory and dummy
have no options.
On Django 6.1, remove every EMAIL_BACKEND = ... (and other EMAIL_* connection
setting) from your own settings, test settings included. Django refuses it next to
MAILERS. Tests need no override: Django’s test runner already swaps every mailer for
the locmem backend.
To compose your own MAILERS (a second alias, a backend that wraps another), build the
entries from the same EmailConfig. The suppression gate takes its transport from another
alias with the inner_mailer option:
MAILERS = {
"default": {
"BACKEND": "django_cfg.core.backends.suppression.SuppressionGateBackend",
"OPTIONS": {"inner_mailer": "transport"}, # required under MAILERS
},
"transport": EmailConfig(backend="gateway", gateway_url=..., gateway_secret=...).to_mailer(),
}On Django 5.2 the same gate is EMAIL_BACKEND = "django_cfg.core.backends.suppression.SuppressionGateBackend"
with EMAIL_GATE_INNER_BACKEND naming the transport class.
To read the configured mailer on either line, use django_cfg.core.backends.mailers:
default_mailer_config() ({"BACKEND", "OPTIONS"} in one shape), default_backend_path(),
default_connection() and HAS_MAILERS. Under MAILERS, settings.EMAIL_BACKEND raises,
and getattr(settings, "EMAIL_BACKEND", "") quietly returns "".
Backend Comparison
| Backend | Use Case | Features |
|---|---|---|
console | Development | Prints emails to console, no actual delivery |
smtp | Production | Standard SMTP delivery (Gmail, SES, Mailgun) |
gateway | Production | POSTs each message as JSON to a trusted HTTP gateway — no provider credentials in Django |
file | Development/staging | Writes emails to files on disk |
memory | Testing | Stores emails in memory (accessible via outbox) |
dummy | Testing | Discards all emails silently |
Usage Examples
Console (Development)
from django_cfg import DjangoConfig
from django_cfg.models import EmailConfig
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
debug: bool = True
email: EmailConfig = EmailConfig(
backend="console" # Prints emails to console
)Generated Django settings:
# Django 5.2
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Django 6.1+
MAILERS = {'default': {'BACKEND': 'django.core.mail.backends.console.EmailBackend'}}Usage:
from django.core.mail import send_mail
send_mail(
'Subject',
'Message body',
'[email protected]',
['[email protected]'],
)
# Email printed to console instead of sentConsole Backend Use Case
Console backend is ideal for:
- Development - See email content without sending
- Testing - Verify email content in unit tests
- Debugging - Inspect email formatting
Not suitable for:
- ❌ Production environments
- ❌ Actual email delivery
- ❌ User notifications
SMTP (Production)
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
debug: bool = False
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.gmail.com",
port=587,
username="[email protected]",
password="your-app-password",
use_tls=True,
default_from="[email protected]",
timeout=30
)Generated Django settings:
# Django 5.2
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your-app-password'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
DEFAULT_FROM_EMAIL = '[email protected]'
EMAIL_TIMEOUT = 30
# Django 6.1+
MAILERS = {
'default': {
'BACKEND': 'django.core.mail.backends.smtp.EmailBackend',
'OPTIONS': {
'host': 'smtp.gmail.com',
'port': 587,
'use_tls': True,
'use_ssl': False,
'timeout': 30,
'username': '[email protected]',
'password': 'your-app-password',
},
},
}
DEFAULT_FROM_EMAIL = '[email protected]'SMTP Credentials Security Never hardcode SMTP credentials:
- Use environment variables for username/password
- Use app-specific passwords (not account passwords)
- Enable TLS encryption (
use_tls=True) - Store credentials in secure secrets manager
Gateway (HTTP Email Gateway)
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
debug: bool = False
email: EmailConfig = EmailConfig(
backend="gateway",
gateway_url="https://email-api.example.com/send",
gateway_secret="your-shared-secret",
default_from="[email protected]",
)Generated Django settings:
# Django 5.2
EMAIL_BACKEND = 'django_cfg.core.backends.gateway.GatewayEmailBackend'
EMAIL_GATEWAY_URL = 'https://email-api.example.com/send'
EMAIL_GATEWAY_SECRET = 'your-shared-secret'
EMAIL_TIMEOUT = 30
DEFAULT_FROM_EMAIL = '[email protected]'
# Django 6.1+ (no EMAIL_GATEWAY_*)
MAILERS = {
'default': {
'BACKEND': 'django_cfg.core.backends.gateway.GatewayEmailBackend',
'OPTIONS': {
'gateway_url': 'https://email-api.example.com/send',
'gateway_secret': 'your-shared-secret',
'timeout': 30,
},
},
}
DEFAULT_FROM_EMAIL = '[email protected]'Each EmailMessage is POSTed as JSON to gateway_url with an Authorization: Bearer header. The gateway owns the provider integration (which ESP, sender identities, rate limits) — Django holds no provider credentials. See the Email Configuration reference for the wire contract and retry behavior.
Gateway Backend Use Case
The gateway backend is ideal when:
- Provider credentials must not live in the Django app (e.g. the ESP is bound to a Cloudflare Worker)
- One gateway serves several apps with centralized sender-identity and rate-limit policy
backend="gateway" requires both gateway_url and gateway_secret — validation fails otherwise.
Provider-Specific Examples
Gmail SMTP
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.gmail.com",
port=587,
username="[email protected]",
password="your-app-password", # Generate at https://myaccount.google.com/apppasswords
use_tls=True,
default_from="[email protected]"
)Gmail Requirements Before using Gmail SMTP:
- ✅ Enable 2-Factor Authentication in Gmail
- ✅ Generate App Password at https://myaccount.google.com/apppasswords
- ✅ Use App Password (not regular password)
- ✅ Verify FROM address matches Gmail account
Common Issues:
- ❌ “Username and Password not accepted” - Use App Password
- ❌ Daily sending limit: 500 emails/day for free accounts
- ❌ Rate limits apply - consider dedicated SMTP for production
AWS SES
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="email-smtp.us-east-1.amazonaws.com",
port=587,
username="YOUR_SES_SMTP_USERNAME",
password="YOUR_SES_SMTP_PASSWORD",
use_tls=True,
default_from="[email protected]" # Must be verified in SES
)AWS SES Configuration Setup Steps:
- Verify sender email/domain in AWS SES console
- Create SMTP credentials (IAM → SES SMTP credentials)
- Request production access (sandbox mode limited to verified emails)
- Configure SPF/DKIM records for better deliverability
Benefits:
- ✅ High deliverability and reputation
- ✅ Pay-as-you-go pricing ($0.10 per 1000 emails)
- ✅ Integrated with AWS ecosystem
- ✅ Detailed sending statistics
Mailgun SMTP
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.mailgun.org",
port=587,
username="[email protected]",
password="your-mailgun-smtp-password",
use_tls=True,
default_from="[email protected]"
)Mailgun Setup
Configuration:
- Use sandbox domain for testing
- Add custom domain for production
- Verify domain with DNS records
- Get SMTP credentials from Mailgun dashboard
Free Tier:
- 5,000 emails/month free
- Email validation API included
- Analytics and tracking
Office 365
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.office365.com",
port=587,
username="[email protected]",
password="your-password",
use_tls=True,
default_from="[email protected]"
)Office 365 Notes Requirements:
- Valid Office 365 subscription
- FROM address must match authenticated user
- Modern authentication may require app password
Limitations:
- 30 messages/minute rate limit
- 10,000 recipients/day limit
- Not recommended for bulk sending
SSL vs TLS
TLS (Port 587) - Recommended
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.example.com",
port=587,
use_tls=True, # ✅ TLS encryption
use_ssl=False,
username="user",
password="pass"
)Advantages:
- Standard port for STARTTLS
- More compatible
- Recommended by most providers
SSL (Port 465)
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.example.com",
port=465,
use_tls=False,
use_ssl=True, # ✅ SSL encryption
username="user",
password="pass"
)Advantages:
- Older standard
- Some providers require it
Environment-Specific Configuration
Choosing by environment
DjangoConfig has no _environment attribute and email is a field, not a property. Decide in the class body, from DJANGO_ENV:
import os
from django_cfg import DjangoConfig, EmailConfig
_env = os.environ.get("DJANGO_ENV", "production")
class MyConfig(DjangoConfig):
secret_key: str = "your-secret-key"
email: EmailConfig = (
EmailConfig(
backend="smtp",
host=os.environ.get("EMAIL_HOST", "localhost"),
port=587,
username=os.environ.get("SMTP_USER"),
password=os.environ.get("SMTP_PASSWORD"),
use_tls=True,
default_from="[email protected]",
)
if _env == "production"
else EmailConfig(backend="console")
)Using Environment Variables
# Production (.env or system ENV)
EMAIL__BACKEND="smtp"
EMAIL__HOST="smtp.example.com"
EMAIL__USERNAME="[email protected]"
EMAIL__PASSWORD="${EMAIL_PASSWORD}"
EMAIL__DEFAULT_FROM="[email protected]"
# Development (.env)
EMAIL__BACKEND="console"# api/environment/loader.py
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class EmailConfig(BaseSettings):
backend: str = Field(default="console")
host: str = Field(default="localhost")
port: int = Field(default=587)
username: str | None = Field(default=None)
password: str | None = Field(default=None)
use_tls: bool = Field(default=True)
default_from: Optional[str] = Field(default=None)
model_config = SettingsConfigDict(
env_prefix="EMAIL__",
env_nested_delimiter="__",
)Advanced Usage
Custom Timeout
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.example.com",
port=587,
username="user",
password="pass",
use_tls=True,
timeout=60 # 60 seconds timeout for slow connections
)Per-site sender
With several sites the sending address stays one (default_from, or SiteConfig.from_email for a site that needs its own). What changes per site is the display name (SiteConfig.from_name, default name) and Reply-To (SiteConfig.support_email). Templates read site_name, site_url, support_email and logo_url from the site. Locale falls back to SiteConfig.locale before en. django-cfg info and show_config mark from_email as (inherited) for a site that uses default_from.
Multiple FROM Addresses
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.gmail.com",
port=587,
username="[email protected]",
password="your-app-password",
use_tls=True,
default_from="[email protected]" # Default FROM
)Usage:
from django.core.mail import send_mail
# Use default FROM
send_mail('Subject', 'Body', None, ['[email protected]'])
# Override FROM
send_mail('Subject', 'Body', '[email protected]', ['[email protected]'])Testing
Send Test Email
from django.core.mail import send_mail
send_mail(
'Test Email',
'This is a test email from Django-CFG',
'[email protected]',
['[email protected]'],
fail_silently=False,
)Test Configuration
# tests/test_email.py
from django.core import mail
from django.test import TestCase
class EmailTestCase(TestCase):
def test_send_email(self):
mail.send_mail('Subject', 'Body', '[email protected]', ['[email protected]'])
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, 'Subject')Django’s test runner sends through the locmem backend on both lines (it swaps
EMAIL_BACKEND on 5.2 and every MAILERS alias on 6.1), so no override is needed. Do not
add @override_settings(EMAIL_BACKEND=...): on Django 6.1 it conflicts with MAILERS.
Security Best Practices
Email Security Critical Email credentials are high-value targets for attackers. Compromised email access can lead to:
- ❌ Spam/phishing sent from your domain
- ❌ Reputation damage and blacklisting
- ❌ Account takeovers via password resets
- ❌ Data breaches through email access
Always follow ALL security practices below.
Environment Variables
1. Use Environment Variables
Never Hardcode Credentials Hardcoded email credentials can be:
- Leaked through version control (git history)
- Exposed in error messages and logs
- Found via code search tools
- Stolen if server is compromised
❌ Bad:
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
username="[email protected]", # ❌ EXPOSED
password="actual-password-123", # ❌ LEAKED
)✅ Good:
import os
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host=os.getenv('EMAIL_HOST'),
port=int(os.getenv('EMAIL_PORT', '587')),
username=os.getenv('EMAIL_USER'),
password=os.getenv('EMAIL_PASSWORD'),
use_tls=True,
default_from=os.getenv('DEFAULT_FROM_EMAIL')
)TLS/SSL Encryption
2. Enable TLS/SSL
Unencrypted Email Without TLS/SSL encryption:
- Passwords transmitted in plain text
- Email content readable by network sniffers
- Man-in-the-middle attacks possible
- Compliance violations (GDPR, HIPAA)
❌ Bad:
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.example.com",
port=25, # ❌ Unencrypted port
use_tls=False, # ❌ No encryption
use_ssl=False, # ❌ No encryption
)✅ Good:
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.example.com",
port=587,
use_tls=True, # ✅ Encryption enabled
username="user",
password="pass"
)App Passwords
3. Use App Passwords
Gmail App Passwords Required Gmail blocks regular passwords for SMTP since May 2022. You must:
- Enable 2-Factor Authentication
- Generate App Password (16-character code)
- Use App Password for SMTP (not account password)
Regular passwords will fail with “Username and Password not accepted” error.
✅ Gmail with App Password:
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.gmail.com",
port=587,
username="[email protected]",
password="abcd efgh ijkl mnop", # ✅ 16-char App Password
use_tls=True
)Domain Verification
4. Validate FROM Address
Domain Reputation Using verified domains improves:
- ✅ Deliverability - Lower spam scores
- ✅ Trust - SPF/DKIM authentication
- ✅ Reputation - Sender reputation tracking
Unverified domains:
- ❌ High spam scores
- ❌ Emails blocked by providers
- ❌ No SPF/DKIM authentication
✅ Good:
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.example.com",
port=587,
username="user",
password="pass",
use_tls=True,
default_from="[email protected]" # ✅ Verified domain
)Troubleshooting
Authentication Failed (Gmail)
Error:
SMTPAuthenticationError: Username and Password not acceptedSolution:
- Enable 2FA in Gmail
- Generate App Password at https://myaccount.google.com/apppasswords
- Use App Password instead of regular password
Connection Timeout
Error:
socket.timeout: timed outSolution:
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.example.com",
port=587,
timeout=60, # Increase timeout
username="user",
password="pass"
)TLS/SSL Errors
Error:
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER]Solution:
# Try port 465 with SSL instead of 587 with TLS
class MyConfig(DjangoConfig):
email: EmailConfig = EmailConfig(
backend="smtp",
host="smtp.example.com",
port=465,
use_tls=False,
use_ssl=True, # Use SSL instead of TLS
username="user",
password="pass"
)Validation
EmailConfig validates:
- Backend - Must be one of:
smtp,console,file,memory,dummy,gateway - Port - Must be 1-65535
- Timeout - Must be 1-300 seconds
- Gateway credentials -
backend="gateway"requires bothgateway_urlandgateway_secret
Example validation error:
# ❌ Invalid backend
EmailConfig(
backend="invalid" # Validation error
)
# ❌ Invalid port
EmailConfig(
backend="smtp",
port=99999 # Validation error
)See Also
- DjangoConfig - Base configuration class
- Configuration Overview - Configuration system overview