How To Send Email in Django and DRF

Sending emails from Django and Django Rest Framework (DRF) can be a crucial feature for various web applications. In this blog, we will guide you through the process of setting up email functionality using a utils.py module, making it reusable and accessible from anywhere in your project.

Note: For this tutorial, we are using our basic skeleton project for Django. You can also download the project from here.

Step 1: Configure Django Email Settings

Ensure that you have configured your email settings properly in your project’s settings.py file. For example:

# settings.py

# ... other settings ...

# Email Configuration
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]'  # Replace with your email address
EMAIL_HOST_PASSWORD = 'your_email_password'  # Replace with your email password

Replace ‘your_smtp_host’, ‘[email protected]’, and ‘your_email_password’ with your actual SMTP server details and email credentials.

Please watch bellow video, to send email using Gmail.

Gmail SMTP Email settings for Django Project

Step 2. Create the Utils Module for Emails

Inside your Django app (let’s say it’s called myapp), create a new Python file named email_utils.py. This module will contain the function for sending emails.

# myapp/email_utils.py

from django.core.mail import send_mail
from django.conf import settings

def send_custom_email(subject, message, recipient_list):
    # Send the email using Django's send_mail function
    send_mail(subject, message, settings.EMAIL_HOST_USER, recipient_list)

The send_custom_email function uses the configured email settings from settings.py to send emails.

To get more understand on django email, you can read this blog.

Step 3. Integrating with Django Views and URL Pattern

Now you can use the send_custom_email function from your views or other parts of the code to send emails. For instance, let’s say you have a view that triggers the email:.

# myapp/views.py

from django.http import HttpResponse
from .email_utils import send_custom_email

def my_email_view(request):
    # ... Your view logic ...

    subject = 'Hello from Django'
    message = 'This is a test email sent from Django.'
    recipient_list = ['[email protected]']  # Replace with the recipient's email addresses

    send_custom_email(subject, message, recipient_list)

    # ... Rest of your view logic ...
    return HttpResponse("Normal Email Send Successfully!")

Create a urls.py file in your app directory (myapp) or add it in main urls.py:

# urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('email/', views.my_email_view, name='normal-email'),
]

Step 6: Test the Email Attachment Functionality

Run your Django development server and navigate to the URL /email/. This will trigger the send_custom_email view, and the email will be sent.

Example: To send multiple with HTML Template

As we will be keeping our email templates in our root directory, please create a folder with name “templates” in root project directory and add a chnage in TEMPLATES > settings.py file.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR, 'templates/',],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Now create a HTML File in “templates” folder with name “email_template.html

<!-- email_template.html -->

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Email Template</title>
</head>
<body>
    <h2>Hello {{ username }},</h2>
    <p>
        Thank you for signing up with our website. Please click the link below to verify your email address:
    </p>
    <a href="{{ verification_link }}">{{ verification_link }}</a>
    <p>
        If you have any questions or need further assistance, feel free to contact us.
    </p>
    <p>
        Best regards,
        Your Website Team
    </p>
</body>
</html>

Here’s a utility method for sending an email with an HTML template using Django’s built-in send_mail function:

# app/email_utils.py

from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags

def send_email_with_template(subject, recipient_list, template_name, context):
    # Render the HTML email template
    html_message = render_to_string(template_name, context)

    # Strip the HTML tags to create a plain text version
    plain_message = strip_tags(html_message)

    # Send the email
    send_mail(subject, plain_message, None, recipient_list, html_message=html_message)

And here is the sample Django Views and URL Pattern:

# app/views.py

from .email_utils import send_email_with_template

def my_email_template_view(request):
    # ... Your view logic ...

    subject = 'Your Subject'
    recipient_list = ['[email protected]']
    template_name = 'email_template.html'
    context = {'username': 'John Doe', 'verification_link': 'http://example.com/verify/123/'}

    send_email_with_template(subject, recipient_list, template_name, context)

    # ... Rest of your view logic ...
    return HttpResponse("Email with Template Sent Successfully!")
# urls.py

from django.urls import path
from . import views

urlpatterns = [
    # ...
    path('email-template/', views.my_email_template_view, name='email-template'),
]

Example: To send multiple mass emails

We need to create a Tuple of messages and send them using send mass mail.

from django.core.mail import send_mass_mail   

message1 = ('Subject here', 'Here is the message', '[email protected]', ['[email protected]', '[email protected]'])
message2 = ('Another Subject', 'Here is another message', '[email protected]', ['[email protected]'])

send_mass_mail((message1, message2), fail_silently=False)

Conclusion

Using the EmailUtils class with Class-Based Views allows you to send emails efficiently and consistently throughout your Django and Django Rest Framework project. This approach centralizes the email logic, making it more maintainable and reusable. Whether you’re sending transactional emails, user notifications, or email confirmations, this setup provides a clean and organized way to handle email functionality in your applications.

Find this tutorial on Github.

Read our Next Tutorial on How to Django Send Email with Attachment

Blogs You Might Like to Read!