Django SMTP: A Complete Guide to Sending Emails
Sending emails in Django is crucial for features like user registration, password resets, or notifications. Django's built-in email framework allows you to send emails easily using an SMTP server.

What is SMTP?
SMTP (Simple Mail Transfer Protocol) is the standard protocol for sending emails across the internet. Django can use SMTP to send emails via Gmail, Outlook, or third-party services like SendGrid.
Configuring Django SMTP Server
Add the following SMTP settings in your settings.py
file:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your_email@gmail.com'
EMAIL_HOST_PASSWORD = 'your_email_password'
Explanation:
- EMAIL_BACKEND: Use Django’s SMTP backend
- EMAIL_HOST: SMTP server address
- EMAIL_PORT: 587 for TLS (or 465 for SSL)
- EMAIL_USE_TLS: Enable secure transport
- EMAIL_HOST_USER: Your email address
- EMAIL_HOST_PASSWORD: Your email password (use environment variables)
Sending Emails in Django
Using send_mail()
function:
from django.core.mail import send_mail
def send_email():
subject = 'Test Email from Django'
message = 'Hello, this is a test email sent from Django SMTP setup.'
from_email = 'your_email@gmail.com'
recipient_list = ['recipient@example.com']
send_mail(subject, message, from_email, recipient_list)
Sending HTML Emails
from django.core.mail import EmailMessage
def send_html_email():
subject = 'HTML Email Test'
message = '<h1>Welcome to Django SMTP!</h1><p>This is an HTML email.</p>'
from_email = 'your_email@gmail.com'
recipient_list = ['recipient@example.com']
email = EmailMessage(subject, message, from_email, recipient_list)
email.content_subtype = "html"
email.send()
Using Django Email Backends
- SMTP Backend (Default)
- Console Backend (For debugging)
- File-based Backend
- Dummy Backend (Disables sending)
Example of console backend for debugging:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Third-Party Services (SendGrid, Mailgun, SES)
EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend'
SENDGRID_API_KEY = 'your_sendgrid_api_key'
Common Issues and Fixes
- Authentication Error: Enable Less Secure Apps in Gmail or use App Passwords.
- Email Not Sent: Check EMAIL_BACKEND, recipient address, and active account.
- SMTP Connection Refused: Verify EMAIL_HOST, EMAIL_PORT, and firewall settings.
Conclusion
Django makes sending emails easy with SMTP configuration, built-in functions, and multiple email backends. Use Gmail SMTP, a console backend for testing, or third-party services like SendGrid to handle emails efficiently.
Frequently Asked Questions
What is SMTP in Django?+
How do I configure SMTP in Django?+
Can Django send HTML emails?+
What are alternative email backends in Django?+
How can I fix SMTP connection errors?+