Django Tutorial
Django Create A Complete Project
Django Template
Django Database Query
Django Form
Django Authentication and Permission Management
Django unittest
Django Advanced
In this tutorial, we'll learn how to send emails using Django's built-in EmailMessage and EmailMultiAlternatives classes.
Prerequisites:
Step 1: Configure Email Settings
1.1. Open your Django project's settings.py
file and add the following email settings:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'your_smtp_server' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'your_email@example.com' EMAIL_HOST_PASSWORD = 'your_email_password'
Replace the placeholder values with your own email server information, email address, and password. For a Gmail account, the configuration would look like this:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'your_gmail_address@gmail.com' EMAIL_HOST_PASSWORD = 'your_gmail_password'
If you're using Gmail, make sure to enable "Less secure apps" in your Gmail account settings. However, it's recommended to use a dedicated email provider for sending emails in production.
Step 2: Sending a Simple Email
2.1. In your app's views.py
, import the necessary modules and create a view function to send a simple email:
from django.core.mail import EmailMessage from django.http import HttpResponse def send_email(request): email = EmailMessage( 'Hello', 'This is the body of the email.', 'from@example.com', ['to@example.com'], reply_to=['another@example.com'], ) email.send() return HttpResponse('Email sent successfully')
Replace the email addresses with appropriate values.
Step 3: Sending an Email with HTML Content
3.1. In your app's views.py
, import the necessary modules and create a view function to send an email with both plain text and HTML content:
from django.core.mail import EmailMultiAlternatives from django.http import HttpResponse def send_html_email(request): subject = 'Hello' text_content = 'This is the plain text content of the email.' html_content = '<strong>This is the HTML content of the email.</strong>' email = EmailMultiAlternatives( subject, text_content, 'from@example.com', ['to@example.com'], reply_to=['another@example.com'], ) email.attach_alternative(html_content, 'text/html') email.send() return HttpResponse('HTML email sent successfully')
Replace the email addresses with appropriate values.
Step 4: Add URL Patterns
4.1. In your app's urls.py
, add new URL patterns for the send_email
and send_html_email
views:
from django.urls import path from . import views app_name = 'myapp' urlpatterns = [ # Other URL patterns... path('send_email/', views.send_email, name='send_email'), path('send_html_email/', views.send_html_email, name='send_html_email'), ]
Step 5: Test Email Sending
5.1. Run your Django development server:
python manage.py runserver
5.2. Visit the URLs corresponding to the send_email
and send_html_email
views (e.g., http://127.0.0.1:8000/myapp/send_email/
and `http://127.0.0.1:8000/myapp/send_html_email/
How to send emails in Django:
send_mail
function to send emails easily.from django.core.mail import send_mail send_mail('Subject', 'Message', 'from@example.com', ['to@example.com'])
Django email backend configuration:
# settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'your-smtp-server.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'your-username' EMAIL_HOST_PASSWORD = 'your-password'
Sending HTML emails in Django:
send_mail
function with html_message
parameter to send HTML-formatted emails.send_mail('Subject', 'Message', 'from@example.com', ['to@example.com'], html_message='<p>This is an HTML message.</p>')
Django email templates and examples:
from django.core.mail import EmailMessage from django.template.loader import render_to_string message = render_to_string('email_template.html', {'context_variable': 'value'}) email = EmailMessage('Subject', message, 'from@example.com', ['to@example.com']) email.send()
Configuring email settings in Django:
DEFAULT_FROM_EMAIL
and SERVER_EMAIL
.# settings.py DEFAULT_FROM_EMAIL = 'webmaster@example.com' SERVER_EMAIL = 'webmaster@example.com'
Django email attachment examples:
attach()
or attach_file()
methods of the EmailMessage
class.from django.core.mail import EmailMessage email = EmailMessage('Subject', 'Message', 'from@example.com', ['to@example.com']) email.attach_file('path/to/file.txt') email.send()
Handling email exceptions in Django:
SMTPException
.from django.core.mail import send_mail, BadHeaderError try: send_mail('Subject', 'Message', 'from@example.com', ['to@example.com']) except BadHeaderError: print('Invalid header found in the email.')
Django email testing strategies:
django.core.mail.backends.console.EmailBackend
for testing or configure a dedicated test email backend.# settings.py if 'test' in sys.argv: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'