Sending Emails with Django From 
Contact us Form

Sending Emails with Django From Contact us Form

Learn how to collect contact form data and send an email using Django

Screenshot 2022-01-26 185312.png

Why need of a send mail option in contact us Page ?

One of the main reason is publishing our email address can be bad idea sometimes ,if a spambot gets hold of mail id , it can windup sending all the spam mails to your account and you account will be in danger That can result in serious security risks from scams or phishing emails. Also having a contact us form will help to get your visitors directly contact you and it can help in getting more leads

Publishing a contact form makes it easy for new customers to get in touch.

If you only have an email link, you’re relying on the customer to go through the trouble of creating an email manually. If they’re using a public or shared computer, they might not be able to create an email at all. So it better to have a contact form . In this Blog we will see how we can get data from contact form and directly send to our mail address using django.core.mail module.

More about this can be found here Textdocs.djangoproject.com/en/4.0/topics/email

Configuring Django

We need to configure settings.py of our project with the below code , we will be using gmail for this , before this make sure you have a gmail account with less secure apps turned on Which can we found here

https://myaccount.google.com/u/4/lesssecureapps

Now we need to configure settings.py with the below code

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "yourmail@gmail.com"
EMAIL_HOST_PASSWORD = "yourpassword"
EMAIL_PORT = '587'

Creating Contact Form

We will be using Django Forms to create a Contact Class that are required in our contact us form Template , define the fields which you want in the class

from django import forms


class ContactForm(forms.Form):
    first_name = forms.CharField(max_length=100, required=True)
    last_name = forms.CharField(max_length=100, required=True)
    email = forms.EmailField(required=True)
    message = forms.CharField(widget=forms.Textarea, required=True)

Now in our Templates Directory of our django app, create a contact_us.html template file add this below code ,

 {% extends 'app/layout.html'%}
 {% load static %}

 {% block content %}

 <style>
.cont-air{
    display: flex;
}
.form-contact{
    margin-top: 10px;
    display: grid;
    width: 700px;
    gap:20px;
}
.form-contact input{
    padding: 5px 20px;
}
.form-contact textarea{
    padding: 5px 20px;
}

button{
    width: 100px;
    height: 30px;
    border-radius: 5px;
    border: none;
    background-color: #df1f1f;
    color: #fff;
    font-size: 14px;
    cursor: pointer;
}

button:hover{
    background-color: darkblue;
    color: #fff;
}

.img-cont{
    width: 100%;
    width: 700px;
}
.img-cont img{
    margin-top: 120px;
    padding-right: 500px;
}

 <div class="cont-air">

    <div style="margin:80px;width: 700px;">
        <h4>Contact us directly if you have any questions</h4>
        <p>
            Please write your name, email address and a message below if you have      any questions.
            One of our staff members will be happy to contact you directly and answer your questions as soon as possible. 
        </p>
        <form method="POST" enctype='multipart/form-data'>
        {% csrf_token %}
            <div class="form-contact">
            <!-- {{form.as_p}} -->
            <input type="text" name="first_name" id="first_name" placeholder="First Name">
            <input type="text" name="last_name" id="last_name" placeholder="Last Name">
            <input type="email" name="email" id="email" placeholder="tanjiro@gmail.com">
            <textarea name="message" id="message" cols="30" rows="10" placeholder="Message"></textarea>
            <button type="submit">Submit</button>
        </div>
        </form>
    </div>

    <div class="img-cont">
        <img src="{% static 'images/haiyuku.png' %}" alt="Haiyuku">
    </div>

</div>
{% endblock %}

Rendering Our Template in Views.py File

Now we need to write a function in views.py to render our contact form template , for that we need to import some things from django.core.mail and our ContactForm from .forms file

from django.core.mail import send_mail, BadHeaderError
from .forms import ContactForm

def contact(request):
if request.method == 'POST':
    form = ContactForm(request.POST)
    if form.is_valid():
        subject = "TEST MAIL"
        body = {
            'first_name': form.cleaned_data['first_name'],
            'last_name': form.cleaned_data['last_name'],
            'email': form.cleaned_data['email'], 
            'message':form.cleaned_data['message'], 
        }
        message = "\n".join(body.values())

        try:
            send_mail(subject,message,settings.EMAIL_HOST_USER, 
                   ['incomingmailid@gmail.com'],fail_silently=False)
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return redirect('/')
form = ContactForm()
return render(request,'app/contact.html',{'form':form})

The send_mail() function is used to send email to the given recipients.

urls.py

We have to add a route in our urls.py file as below

from django.urls import path
from . import views


urlpatterns = [
   path('contact/',views.contact, name='contact'),
]

Update Your Changes and Start your Server Now And that's it!