Send Email
Send emails from your Django application
📧 What is Django Email?
Django's email functionality lets you send emails from your application for notifications, password resets, and user communication. It supports multiple email backends including SMTP, console, and third-party services.
from django.core.mail import send_mail
send_mail(
'Subject',
'Message body',
'[email protected]',
['[email protected]']
)
Email Features
Simple Emails
Send plain text messages
send_mail('Hi', 'Hello!', '[email protected]', ['[email protected]'])
HTML Emails
Send styled HTML content
send_mail(html_message='<h1>Hi</h1>')
Attachments
Include files in emails
email.attach_file('file.pdf')
Multiple Recipients
Send to many users at once
send_mass_mail(messages)
🔹 Configure Email Settings
Set up email configuration in your settings.py file. For development, use console backend to see emails in terminal. For production, configure SMTP with your email provider.
# settings.py
# For Development (prints to console)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# For Production (Gmail example)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your-app-password'
DEFAULT_FROM_EMAIL = '[email protected]'
Gmail Setup:
- Enable 2-factor authentication
- Generate app password
- Use app password in settings
🔹 Send Simple Email
Use Django's send_mail function to send basic text emails. This is the easiest way to send emails and works great for simple notifications and messages.
# views.py
from django.core.mail import send_mail
from django.http import HttpResponse
def send_welcome_email(request):
send_mail(
subject='Welcome to Our Site!',
message='Thank you for signing up. We are excited to have you!',
from_email='[email protected]',
recipient_list=['[email protected]'],
fail_silently=False,
)
return HttpResponse('Email sent successfully!')
Console Output (Development):
🔹 Send HTML Email
Create visually appealing emails using HTML content. HTML emails can include styling, images, and formatted text for a professional appearance.
# views.py
from django.core.mail import send_mail
def send_html_email(request):
html_message = """
<html>
<body style="font-family: Arial, sans-serif;">
<h1 style="color: #007bff;">Welcome!</h1>
<p>Thank you for joining our community.</p>
<a href="https://mysite.com" style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none;">
Visit Our Site
</a>
</body>
</html>
"""
send_mail(
subject='Welcome!',
message='Plain text version', # Fallback
from_email='[email protected]',
recipient_list=['[email protected]'],
html_message=html_message,
)
return HttpResponse('HTML email sent!')
🔹 Send Email with Template
Use Django templates to create reusable email content. This approach keeps your email HTML separate from Python code and makes it easier to maintain.
<!-- templates/emails/welcome.html -->
<html>
<body>
<h1>Hello {{ user.first_name }}!</h1>
<p>Welcome to {{ site_name }}.</p>
<p>Your account has been created successfully.</p>
</body>
</html>
# views.py
from django.core.mail import send_mail
from django.template.loader import render_to_string
def send_template_email(request, user):
html_message = render_to_string('emails/welcome.html', {
'user': user,
'site_name': 'MySite'
})
send_mail(
subject='Welcome to MySite',
message='Welcome!', # Plain text fallback
from_email='[email protected]',
recipient_list=[user.email],
html_message=html_message,
)
return HttpResponse('Template email sent!')
🔹 Send Email with Attachment
Attach files to your emails using EmailMessage class. This is useful for sending invoices, reports, or any documents to users.
# views.py
from django.core.mail import EmailMessage
def send_email_with_attachment(request):
email = EmailMessage(
subject='Your Invoice',
body='Please find your invoice attached.',
from_email='[email protected]',
to=['[email protected]'],
)
# Attach file from filesystem
email.attach_file('invoices/invoice_123.pdf')
# Or attach file from memory
email.attach('report.txt', 'File content here', 'text/plain')
email.send()
return HttpResponse('Email with attachment sent!')
🔹 Send Bulk Emails
Send multiple emails efficiently using send_mass_mail. This function opens a single connection to send all emails, making it faster than sending individually.
# views.py
from django.core.mail import send_mass_mail
def send_newsletter(request):
users = User.objects.all()
messages = []
for user in users:
message = (
'Newsletter - March 2024', # Subject
f'Hi {user.first_name}, check out our latest updates!', # Body
'[email protected]', # From
[user.email], # To
)
messages.append(message)
send_mass_mail(messages, fail_silently=False)
return HttpResponse(f'Sent {len(messages)} emails!')
Output:
Sent 150 emails!