Django — Email
Email Settings
# settings.py
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-password'
DEFAULT_FROM_EMAIL = 'My Site <noreply@example.com>'
Send Email
from django.core.mail import send_mail
send_mail(
'Subject here',
'Here is the message.',
'from@example.com',
['to@example.com'],
fail_silently=False,
)
Send HTML Email
from django.core.mail import EmailMultiAlternatives
msg = EmailMultiAlternatives(
'Subject',
'Plain text body',
'from@example.com',
['to@example.com']
)
msg.attach_alternative('<h1>HTML body</h1>', 'text/html')
msg.send()
Email Templates
from django.template.loader import render_to_string
html_message = render_to_string('email/welcome.html', {
'user': user,
'site_name': 'My Site',
})
send_mail('Welcome!', '', 'from@example.com', [user.email],
html_message=html_message
)
Connection
from django.core.mail import get_connection
with get_connection() as connection:
msg1 = EmailMessage('Sub1', 'Body1', 'from@ex.com', ['to@ex.com'], connection=connection)
msg2 = EmailMessage('Sub2', 'Body2', 'from@ex.com', ['to@ex.com'], connection=connection)
msg1.send()
msg2.send()
Mini Practice
- Configure email settings
- Send a simple email
- Send HTML email
- Use email templates
Up Next
Continue with Pagination — paginating querysets.
Related Topics
Frequently Asked Questions about Email
What is Email in Django?
Email is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Email?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Email.
Why is Email important in Django?
Email is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.