In Contact Form, Django, Form submissions, Sending emails

In this SayHelloWorld tutorial we are going to build a Django contact form that sends emails. We will build this in a minimal setup django application.

Source Code: Link

Steps:

  1. Obtain email host server name information and port number
  2. Configure your email account in Django settings.py with  the django.core.mail module
  3. Import libraries into view
  4. Configure view to handle post request.

 

1 – Obtain your email provides server name and port number.

If you are using zoho as your email provider you can get your information in this link. If you are using another email provider you can simple do google search for “(Provider) smtp server configuration” and you should be able to find the proper information.

2 – Configure in settings.py

In settings.py we need to configure our settings so Django has access to our account and send emails. Django will need the server name (EMAIL_HOST), our email (EMAIL_HOST_USER),  email account password (EMAIL_HOST_PASSWORD), email provider port name (EMAIL_PORT), security type TLS or SSL (EMAIL_USE_TLS) and finally the email back end (EMAIL_BACKEND) wich in our case will be “jango.core.mail.backends.smtp.EmailBackend”

3 – Import Libraries

In our views file we will need to import the send_mail() function from django.core.mail settings from django.conf.

The send mail function is what we use to send our email. it takes in the following parameters.

  • Subject
  • Message
  • Email that will send the message
  • Email’s that will receive the message (List)
  • fail_silently – A true or false value that raises error if email fails (We set to false)

By importing “settings” we now have access to the email host user which we will see in the next step.

4 – Configure View For Post Request

The final step to sending an email is handling the data send from the form. In our view we put our message in a the variable message then write our send mail function.

  • We will set our subject to “Contact Form” so our admin knows wich form this message is comming form.
  • We added the message varible into the message field.
  • For the email sending we accessed our settings file and used the EMAIL_HOST_USER we set earlier.
  • Finally we added our reciever e email wich is our admin and set fail siletnly to be false because we dont want an error for now if our email didnt send.

Now go ahead and test out your contact form and make sure the email works. If you need help configuring the form you can check out the source code here: Link

Adding a template with custom formatting to emails: Link

 

Contact Us

We're not around right now. But you can send us an email and we'll get back to you, asap.