Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Mail Sending

In this tutorial, we'll learn how to send emails using Django's built-in EmailMessage and EmailMultiAlternatives classes.

Prerequisites:

  • Basic knowledge of Python
  • Familiarity with Django framework
  • A Django project set up and running

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/

  1. How to send emails in Django:

    • Description: Django provides a convenient send_mail function to send emails easily.
    • Code Example:
      from django.core.mail import send_mail
      
      send_mail('Subject', 'Message', 'from@example.com', ['to@example.com'])
      
  2. Django email backend configuration:

    • Description: Configure the email backend in Django settings to determine how emails are sent (e.g., SMTP, console).
    • Code Example:
      # 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'
      
  3. Sending HTML emails in Django:

    • Description: Use the send_mail function with html_message parameter to send HTML-formatted emails.
    • Code Example:
      send_mail('Subject', 'Message', 'from@example.com', ['to@example.com'], html_message='<p>This is an HTML message.</p>')
      
  4. Django email templates and examples:

    • Description: Create email templates using Django's template system for more complex email content.
    • Code Example:
      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()
      
  5. Configuring email settings in Django:

    • Description: Configure various email-related settings in Django settings.py, such as DEFAULT_FROM_EMAIL and SERVER_EMAIL.
    • Code Example:
      # settings.py
      DEFAULT_FROM_EMAIL = 'webmaster@example.com'
      SERVER_EMAIL = 'webmaster@example.com'
      
  6. Django email attachment examples:

    • Description: Attach files to emails using the attach() or attach_file() methods of the EmailMessage class.
    • Code Example:
      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()
      
  7. Handling email exceptions in Django:

    • Description: Handle exceptions that may occur during the email sending process, such as SMTPException.
    • Code Example:
      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.')
      
  8. Django email testing strategies:

    • Description: Use Django's django.core.mail.backends.console.EmailBackend for testing or configure a dedicated test email backend.
    • Code Example:
      # settings.py
      if 'test' in sys.argv:
          EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'