Building an Email Contact Form with Django


squirrel-with-letter

If you’ve spent any time browsing the web, you’re probably aware that a contact form is a crucial component for many websites. It serves as a direct line of communication between users and website owners, making it easy for visitors to reach out with inquiries, feedback, or support requests. In this tutorial, we will guide you through the process of creating a simple yet functional email contact form using Django, a web framwork based on Python. By the end of this tutorial, you’ll not only have a working contact form but also a deeper understanding of Django's form handling and email functionalities. Let’s get started!

headline

0. Prerequisites

In this tutorial, we’ll take a hands-on approach to create a simple email contact form. While this contact form is fully functional, it’s important to note that it’s designed for learning purposes only and may not be suitable for a production environment. We won’t be incorporating any spam protection, and we'll rely on Python's built-in mail server instead of a more robust mail server option.


Before creating the email contact form, ensure you have a Django project set up with a virtual environment, an app, an HTML template, and the appropriate routing in place. If you need a little refresher on any of these components, feel free to check out my previous tutorial for a comprehensive overview.

Supppose: In urls.py: urlpatterns = [ path('', views.home, name="home"), path('contact.html', views.contact, name="contact"), ]

1. Add the form to the html template

Blogpost sub-headline

in the templates folder of your app, create a contact.html. with this content:

Contact Page screenshot 2

In this HTML code for the contact form, you’ll notice a blend of standard HTML and Django's templating language, which is easily identifiable by the curly brackets and ampersand signs. The method="POST" statement plays a crucial role here; it defines the type of HTTP request that will be initiated when a user submits the form. Understanding HTTP requests is fundamental to web communication. While the most commonly used request is GET—used to retrieve content from a server—a POST request signifies that we want to send data back to the server, like submitting the form data rather than just reading information.

In Django, every form must include the {% csrf_token %}, which is essential for protecting against Cross-Site Request Forgery attacks. If you're curious to learn more about this security measure, I encourage you to explore additional resources on the topic.

Next up, we have our various input elements, represented by the tag. In this case, all input types are set to "text." Each input element is assigned a name, which will be vital for capturing the user’s entries, as you'll see in the next steps. The placeholder attribute is optional; it simply provides a hint of what information is expected as long as the field remains empty. To wrap things up, we’ll add a submit button labeled "Send Message."

Lastly, within the range of {% if msg_name %} and {% endif %}, we create a special section that only appears after the user submits the form. Before submission, there won't be any msg_name in the context, and thus, no message will be displayed. The context is a special variable we can hand over to the template before rendering it to the user. You'll soon see this in action. Our goal here is to offer users personalized feedback once they’ve sent their message, reassuring them that their submission is on its way.

2. Create function in views.py

Paragraph heading

As a next step, you’ll want to create a corresponding function in views.py that captures the content submitted through the form and processes it accordingly. If there’s no user input, this function can simply render the website template as is, ensuring a smooth user experience. This way, we can handle both form submissions and regular visits to the page in one view function.

def contact(request): if request.method == "POST": msg_name = request.POST['name'] msg_email = request.POST['email'] msg_subject = request.POST['subject'] msg_message = request.POST['message'] # send an email to the dentist send_mail( 'message from ' + msg_name + ' ' + msg_subject, # subject msg_message, # message msg_email, # from email ['dentist@gmail-com'], # To Email. dummy email! ) return render(request, 'dwebsite/contact.html', {'msg_name': msg_name}) else: return render(request, 'dwebsite/contact.html', {})

3. Setup Mailserver

Blogpost sub-headline

for this form to actually send an email after submission, you need a running mailserver. Fortunately, send_mail ships with a mini mailserver you can use for testing and debugging purposes. You have to include this in your settings.py to get up and running with it:

# test method for sending email: pythons own sendmail server # Email Settings EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 # different than 8000 EMAIL_HOST_USER = '' # put this in OS environ EMAIL_HOST_PASSWORD = '' # put this in OS environ EMAIL_USE_TLS = False # set True for production # EMAIL_USE_SSL = False # same

Contact Page screenshot 2

4. Start Mailserver and test application

Paragraph heading

For starting this mini-mailserver, open a fresh terminal. inside the virtual environment, go to manage.py level. Run this command in the termibal: python -m smtpd -n -c DebuggingServer localhost:1025

5. Final word on sending mail in production

Blogpost sub-headline

When it comes to sending emails in a production environment, the approach you take largely depends on the email provider used by the website owner. I encourage you to take a moment to Google the phrase "send_email with " to gather specific information relevant to your situation. You’ll need details like the host, port, and the website owner’s email address.

For example, if you’re using Gmail, it’s important to note that, by default, Gmail doesn’t permit third-party applications to send emails. In the past, enabling the "allow less secure apps" setting made this possible, but that’s not the most secure route. Instead, a more effective approach is to create a dedicated app in Google and generate a specific password for it. This way, you won’t have to share your main Google password, enhancing your security.

To set this up, remember to enable two-factor authentication (2FA) on the Google account first. This added layer of security not only protects your account but also gives you peace of mind as you engage with your users. By following these steps, you’ll be well on your way to implementing a reliable and secure email-sending solution for your production website.

Contact Page screenshot 2

Recap

Paragraph heading

Fshort recap: In thsi blogpost, we...

Blog Posts

Start with Django

If you’ve been curious about web development, starting your journey with Django might just be the right choice for you. As a powerful framework, Django is designed to help developers build web applications more easily and efficiently.
Read more

HTTP requests: A beginner's guide

If you're just starting your web development journey, you've likely come across the term "HTTP requests." But what exactly are they, and why are they so important? Don’t worry; we’re here to break it down in a simple and approachable way!
Read more

Your first Node Server

Node.js is a powerful, open-source JavaScript runtime that allows you to build server-side applications with ease. If you’re looking to get started with web development beyond the client side, setting up your first Node server is a great way to begin.
Read more

Email Contact Form in Django

You’re probably aware that a contact form is a crucial component for many websites. In this tutorial, we will guide you through the process of creating a simple yet functional email contact form using Django.
Read more

Your First Full-Stack App

In this blog post, we'll explore how to set up a modern web application using React for the front end, Vite for a fast development experience, and Node.js for your backend. This powerful combination allows you to build dynamic, responsive applications with ease.
Read more

Routing in Express

In Express, a popular web framework for Node.js, setting up routes allows you to build dynamic, user-friendly applications effortlessly. In this tutorial, we’ll cover the essential concepts of routing in Express, including how to create routes, define route parameters, and handle different HTTP methods.
Read more