Django send email on contact form submission
In this article, you will learn how to collect contact form data and send an email using Django.
Gathering contact form data and delivering to the mail inbox is a very common task during web development. Django makes this very dynamic as we can send hundreds of mail in a single day. For this, we will create an HTML contact form template. When user hits the submit button, the data will be sent to the 'views.py' file, which will validate the form data and send an email to the given recipients.
These are the step-by-step process to gather data from the contact form template and send it to the specified recipients.
Activate Virtualenv and Create Project
First, we have activated the 'virtualenv' and created a project 'contactform' and a new app 'contact' using the given command -
(env) c:\python37\Scripts\projects>django-admin startproject contactform
(env) c:\python37\Scripts\projects>cd contactform
(env) c:\python37\Scripts\projects\contactform>django-admin startapp contact
Contact Form Template
We have created a new HTML file 'contact.html' in the 'templates' directory of the'contact' app -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<form method="POST" class="post-form" action="/thanks">
{% csrf_token %}
<div class="container">
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" class="form-control" id="subject" />
</div>
<div class="form-group">
<label for="sender">Sender</label>
<input type="email" class="form-control" id="sender" placeholder="This email address is being protected from spambots. You need JavaScript enabled to view it. "/>
</div>
<div class="form-group">
<label for="cc">CC</label>
<input type="text" class="form-control" id="cc"/>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</body>
</html>
Here is another HTML file 'thanks.html'. After successful form submission, the user is redirected to this page.
<body>
<h3>Thanks for your contact!</h3>
</body>
views.py
We have written the following code in 'views.py' -
from django.shortcuts import render
from contact.forms import ContactForm
from django.core.mail import send_mail
# Create your views here.
def contact(request):
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc = form.cleaned_data['cc']
recipients = [This email address is being protected from spambots. You need JavaScript enabled to view it. ']
recipients.append(sender)
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/thanks/')
else:
form = ContactForm()
return render(request,'contact.html',{'form':form})
The send_mail() function is used to send email to the given recipients.
urls.py
We have added these url links to the 'urls.py' file -
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from contact import views
urlpatterns = [
path('admin/', admin.site.urls),
path('contact', views.contact),
path('/thanks/',TemplateView.as_view(template_name='thanks.html'))
]
Run Application
Now, let's migrate and run the application using the following command -
(env) c:\python37\Scripts\projects\contactform>python manage.py makemigrations
No changes detected
(env) c:\python37\Scripts\projects\contactform>python manage.py runserver
Related Articles
Generate and download a CSV file in DjangoDjango ajax GET and POST request
Display image from database in Django
How to read and write a file using Django
Django pass variable from view to HTML template
Get data from MySQL in Django View with Models
Django serialize queryset into JSON and display in template
Django Custom User Model SignUp, Login and Logout
Django Export Model Data to CSV
How to get data from MySQL in Django View with Models
Windows commands to Create and Run first Django app
Django Send Mail on Contact form submission
How to insert data in MySQL database from an HTML form using Django
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python