Build an Email Sender App in Django

When I first started working with Django, sending emails programmatically was one of those essential tasks that every web app needed. I’ve developed a simple approach to building email sender apps in Django that is both reliable and easy to maintain.

In this tutorial, I’ll walk you through how to create a simple yet powerful email sender app using Django. We’ll cover setting up your Django project, configuring email settings, creating a form to send emails, and handling the backend logic. I’ll also share some tips based on my experience to make your app production-ready.

Let’s get started.

Set Up Your Django Project

If you haven’t already, start by creating a new Django project and an app where we’ll build our email sender.

django-admin startproject emailproject
cd emailproject
python manage.py startapp emailsender

Add the emailsender app to your INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    # other apps
    'emailsender',
]

Read Python Django Import Functions

Configure Email Settings in Django

To send emails, Django needs to know the email server details. For this example, I’ll use Gmail’s SMTP server, which is common in the USA for testing and small projects. Make sure you have a Gmail account with “App Passwords” enabled if you have 2FA.

Add the following to your 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'  # Replace with your email
EMAIL_HOST_PASSWORD = 'your_app_password'  # Use app password, not your Gmail password

Note: Never hardcode sensitive credentials in production. Use environment variables or Django’s decouple package for secure management.

Create the Email Form

Next, create a simple form where users can input the recipient’s email, subject, and message.

In emailsender/forms.py:

from django import forms

class EmailForm(forms.Form):
    recipient = forms.EmailField(label='Recipient Email', max_length=254)
    subject = forms.CharField(max_length=255)
    message = forms.CharField(widget=forms.Textarea)

This form ensures basic validation like proper email format and non-empty fields.

Check out Django User Registration with Email Confirmation

Build the View to Handle Email Sending

In emailsender/views.py, we’ll create a view to display the form and send the email upon submission.

from django.shortcuts import render
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
from .forms import EmailForm

def send_email_view(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            recipient = form.cleaned_data['recipient']
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            from_email = 'your_email@gmail.com'  # Same as EMAIL_HOST_USER

            try:
                send_mail(subject, message, from_email, [recipient])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return HttpResponse('Email sent successfully!')
    else:
        form = EmailForm()
    return render(request, 'emailsender/send_email.html', {'form': form})

Create the Template

Create a folder templates/emailsender/ inside your app directory and add send_email.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Send Email</title>
</head>
<body>
    <h1>Send an Email</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Send</button>
    </form>
</body>
</html>

Read Create a Dictionary Application in Django

Add URL Patterns

In emailsender/urls.py:

from django.urls import path
from .views import send_email_view

urlpatterns = [
    path('send-email/', send_email_view, name='send_email'),
]

Include this in the main project’s urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('emailsender.urls')),
]

Check out Create a Music Player Application using Django

Test Your Email Sender App

Run the Django development server:

python manage.py runserver

Navigate to http://127.0.0.1:8000/send-email/ and you’ll see the form. Fill in the recipient’s email, subject, and message, then hit send.

You can see the output in the screenshot below.

django email

If everything is configured correctly, the recipient should get the email almost instantly.

Alternative Method: Use Django’s Console Email Backend for Testing

While developing, you might not want to send real emails. Django provides a console backend that prints emails to the terminal instead.

In settings.py, switch the email backend:

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

This way, you can test email functionality without worrying about actual email delivery or credentials.

Read Django Programming Error: Column does not exist.

Tips from Experience

  • Security: Always use environment variables for your email credentials in production.
  • Error Handling: Improve user experience by adding messages for success/failure instead of plain HttpResponse.
  • Email Templates: For professional emails, use HTML templates with Django’s EmailMultiAlternatives.
  • Bulk Emails: For sending to multiple recipients, pass a list to send_mail() or consider Django packages like django-anymail.
  • Async Sending: For better performance, send emails asynchronously using Celery or Django Q.

Building an email sender app in Django is easy once you understand the basic components: configuration, form handling, and sending emails. Whether you’re creating a contact form for a local business in the USA or building notification systems for enterprise apps, this approach scales well.

I hope you found this guide useful.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.