Sending emails is one of the most important features in any web application. Whether it's for user registration, password resets, or notifications, sending emails makes your app more useful and interactive.
In this blog, we'll walk through how to send emails using Django, the popular Python web framework. We'll go step-by-step from setting up the email backend to actually sending a test email. Even if you're new to Django or web development, don’t worry—this guide is for you.
Why Send Emails from Your Django App?
Before we jump into the code, let’s talk about a few real-life scenarios where email functionality is useful:
-
Welcome emails when a user signs up
-
Password reset or account verification links
-
Weekly newsletters or announcements
-
Notification emails for comments, orders, or support tickets
Adding this feature improves the user experience and helps you build a more professional and interactive application.
Step 1: Create a Django Project (If You Haven't Already)
If you haven’t created a Django project yet, start by installing Django using pip:
pip install django
Then create your project:
django-admin startproject myemailproject
cd myemailproject
Create an app:
python manage.py startapp emailapp
Don’t forget to add your app (emailapp
) to INSTALLED_APPS
in settings.py
.
Step 2: Configure Email Settings in settings.py
Django uses the EMAIL_BACKEND
setting to define how it sends emails. The most common setup is using Gmail’s SMTP server, which works perfectly for small and test projects.
Here’s how you can set it up in your settings.py
:
# 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 = 'youremail@gmail.com' # Your Gmail address
EMAIL_HOST_PASSWORD = 'yourapppassword' # App-specific password
Important: If you use Gmail, you’ll need to generate an app password instead of using your Gmail login password. Google blocks less secure apps by default.
Step 3: Create a Simple Email View in Django
Let’s write a simple Django view that sends an email when you visit a URL.
In emailapp/views.py
, add the following code:
from django.core.mail import send_mail
from django.http import HttpResponse
def send_test_email(request):
send_mail(
subject='Hello from Django',
message='This is a test email sent from Django.',
from_email='youremail@gmail.com',
recipient_list=['recipient@example.com'],
fail_silently=False,
)
return HttpResponse("Email sent successfully!")
Step 4: Add a URL to Trigger the Email
Now let’s map the view to a URL so we can test it.
In emailapp/urls.py
(you may need to create this file):
from django.urls import path
from . import views
urlpatterns = [
path('send-email/', views.send_test_email, name='send_email'),
]
Then, include the app's URLs in your project’s main urls.py
file (myemailproject/urls.py
):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('emailapp.urls')),
]
Step 5: Run the Server and Send the Email
Now everything is set up! Just run your server:
python manage.py runserver
Then visit:
http://127.0.0.1:8000/send-email/
If everything is correct, Django will send the email, and you’ll see the message: "Email sent successfully!"
How to Send HTML Emails in Django
Plain text is great, but HTML emails look more professional. Let’s see how to send an HTML email instead of plain text.
Replace send_mail
with EmailMessage
or EmailMultiAlternatives
like this:
from django.core.mail import EmailMultiAlternatives
def send_html_email(request):
subject = 'Welcome to Our Website'
from_email = 'youremail@gmail.com'
to = ['recipient@example.com']
text_content = 'Thank you for signing up.'
html_content = '<h2>Welcome!</h2><p>Thanks for joining our platform.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, to)
msg.attach_alternative(html_content, "text/html")
msg.send()
return HttpResponse("HTML email sent successfully!")
This allows you to send both plain text and HTML versions of the email, ensuring compatibility with most email clients.
Sending Emails in Django Using a Form
Let’s say you want users to fill a form and receive an email. Here's a basic example.
Create a Form
In emailapp/forms.py
:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
email = forms.EmailField()
Create a View to Handle Form and Send Email
from django.shortcuts import render
from .forms import ContactForm
from django.core.mail import send_mail
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
from_email = form.cleaned_data['email']
send_mail(subject, message, from_email, ['youremail@gmail.com'])
return HttpResponse("Thanks for contacting us!")
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
Create the HTML Template
In emailapp/templates/contact.html
:
<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<h2>Contact Us</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
</body>
</html>
Common Email Errors and Fixes
Here are a few common issues you might face:
-
Authentication errors: Make sure you're using the correct app password (not your Gmail login).
-
Port issues: Use port
587
withEMAIL_USE_TLS = True
, or port465
withEMAIL_USE_SSL = True
. -
Firewall or network issues: Sometimes hosting environments block outgoing SMTP connections.
Always test on a local machine first before deploying to production.
Conclusion
That’s it! You’ve just learned how to send emails in Django using Python. From basic text emails to full HTML messages and forms, Django gives you everything you need.
Here's a quick summary of what we covered:
-
Setting up SMTP with Gmail
-
Sending basic and HTML emails
-
Handling emails via user forms
-
Troubleshooting common issues
By adding email functionality, you make your app feel complete and user-friendly. It’s also a step toward building more professional, real-world applications.