Sending Mail in Python using Django Framework Tutorial

In this tutorial, we will tackle about Sending Mail in Python using Django Framework. We will be using the GMail STMP as our Email Host for sending mail. Here, you will learn the process or steps that need to be done to send mail from your Python Django App. We will be creating a simple Django Project that contains a Send Us a Message Form. Using the said form, the app will be sending an email to the site email receiver.

Gettign Started

Download Python and pip in your local machine.

Download Django using PIP. Follow the command below.

  pip install Django

Let's start the coding ...

Creating a Django Project

First, we nee d to create a new django project. You can name your project whatever you like. In my case, I will be naming my project as 'send_mail'. Open your terminal or command prompt.

Change the current directory to the path you want to store your source code.

  cd C://

Creating a Django Project

  django-admin startproject send_mail

Creating a Django App

Next, we will be creating our projects app. In my case my app name will be 'contact'.

In your terminal, you will enter the command same as below. Change the 'contact' to your desired app name.

Change you current directory to your django project directory.

  cd send_mail
  python manage.py startapp contact

Configure Django Settings

Next, we will be configuring the projects settings.py file. This file is located inside the project root folder. Open this file in your preferred Text Editor such as sublime text or notepadd++.

Add your app in the 'INSTALLED_APPS'. Confirm your App Name by opening the file Your App DIR >> apps.py

  1. from django.apps import AppConfig
  2.  
  3.  
  4. class ContactConfig(AppConfig):
  5. default_auto_field = 'django.db.models.BigAutoField'
  6. name = 'contact'

In your settings.py.

  1. INSTALLED_APPS = [
  2. 'django.contrib.admin',
  3. 'django.contrib.auth',
  4. 'django.contrib.contenttypes',
  5. 'django.contrib.sessions',
  6. 'django.contrib.messages',
  7. 'django.contrib.staticfiles',
  8. 'contact.apps.ContactConfig'
  9. ]

Next, add the email confoguration in the same file (settings.py). Add the following into the file.

  1. #Email Configuration
  2. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
  3. EMAIL_HOST = 'smtp.gmail.com'
  4. EMAIL_PORT = '587'
  5. EMAIL_HOST_USER = 'Your Email Here'
  6. EMAIL_HOST_PASSWORD = 'Your Password Here'
  7. EMAIL_USE_TLS = True

Configuring the URL Dispatcher

Next, we will be configuring our app URLs. To do that, create a new python file inside your app directory naming urls.py. Then, add the following code.

  1. from django.urls import path
  2. from . import views
  3. urlpatterns = [
  4. path('', views.contact_form, name="contact-form"),
  5. ]

Next, include the app urls.py file in the project urls.py. This file is located at the project's root path.

  1. from django.contrib import admin
  2. from django.urls import path, include
  3.  
  4. urlpatterns = [
  5. path('admin/', admin.site.urls),
  6. path('', include('contact.urls'))
  7. ]

Creating the View

Next, we will be creating our application view. In your application directory, you will see a views.py file. Open the file in your text editor. Then, follow the script below. Make sure that the post data name you will enter will be exactly as your UI text fields name later.

  1. from django.shortcuts import render
  2. from django.core.mail import send_mail
  3.  
  4. # Create your views here.
  5.  
  6. def contact_form(request):
  7. context = {}
  8. if request.method == 'POST':
  9. name = request.POST['name']
  10. email = request.POST['email']
  11. message = "From: "+ email + "\n"
  12. message += "Sender Name: "+ name + "\n\r\n\r"
  13. message += "-------------------------------------------------------"
  14. message += "\n\r\n\r"
  15.  
  16. message += request.POST['message']
  17.  
  18. try:
  19. send_mail(
  20. 'SITE Inquiry - '+ name,# subject,
  21. message,#message
  22. email,# from email
  23. ['[email protected]'],# to email,
  24. #fail_silently=False
  25. )
  26. context = {'mail_response':True}
  27. except Exception as err:
  28. raise err
  29.  
  30. return render(request,'contact_information.html',context)

Creating the Template

Lastly, we will be creating the app user interface. To do that, create a new directory inside your application directory and name it as templates. Then, create a new html file, in my case as you can see at the views.py file script I provided, I rendered an HTML file naming contact_information.html so this should be the file I will create.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Contact Information | XYZ Site</title>
  7. <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  8. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  9. html,
  10. body {
  11. height: 100%;
  12. width: 100%;
  13. }
  14.  
  15. #pre-loader {
  16. position: absolute;
  17. top: 0;
  18. left: 0;
  19. width: 100%;
  20. height: 100%;
  21. display: flex;
  22. align-items: center;
  23. justify-content: center;
  24. backdrop-filter: brightness(.8);
  25. z-index: 999999999;
  26. }
  27.  
  28. .lds-ring {
  29. display: inline-block;
  30. position: relative;
  31. width: 80px;
  32. height: 80px;
  33. }
  34.  
  35. .lds-ring div {
  36. box-sizing: border-box;
  37. display: block;
  38. position: absolute;
  39. width: 64px;
  40. height: 64px;
  41. margin: 8px;
  42. border: 8px solid #fff;
  43. border-radius: 50%;
  44. animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
  45. border-color: #fff transparent transparent transparent;
  46. }
  47.  
  48. .lds-ring div:nth-child(1) {
  49. animation-delay: -0.45s;
  50. }
  51.  
  52. .lds-ring div:nth-child(2) {
  53. animation-delay: -0.3s;
  54. }
  55.  
  56. .lds-ring div:nth-child(3) {
  57. animation-delay: -0.15s;
  58. }
  59.  
  60. @keyframes lds-ring {
  61. 0% {
  62. transform: rotate(0deg);
  63. }
  64. 100% {
  65. transform: rotate(360deg);
  66. }
  67. }
  68. </style>
  69. var loader = document.createElement('div')
  70. loader.setAttribute('id', 'pre-loader')
  71. loader.innerHTML = '<div class="lds-ring"><div></div><div></div><div></div><div></div></div>'
  72.  
  73. function start_loader() {
  74. if (!!document.getElementById('pre-loader'))
  75. document.getElementById('pre-loader').remove();
  76. document.querySelector('body').appendChild(loader)
  77. }
  78.  
  79. function end_loader() {
  80. setTimeout(() => {
  81. if (!!document.getElementById('pre-loader'))
  82. document.getElementById('pre-loader').remove();
  83. }, 500)
  84. }
  85. window.addEventListener('load', function() {
  86. end_loader()
  87. document.getElementById('email-form').addEventListener('submit', function() {
  88. start_loader()
  89. })
  90. })
  91. </script>
  92. </head>
  93.  
  94. <body class="bg-dark bg-gradient bg-opacity-50">
  95. start_loader()
  96. </script>
  97. <nav class="nav bg-light py-3">
  98. <div class="container">
  99. <h4 class="text-center"><b>Simple Contact Form Page</b></h4>
  100. </div>
  101. </nav>
  102. <section class="content pt-4">
  103. <div class="container">
  104. <div class="row justify-content-center">
  105. <div class="col-lg-7 col-md-10 col-sm-12 col-xs-12">
  106. <div class="card card-default border rounded-0">
  107. <div class="card-body">
  108. <div class="container-fluid">
  109. {% if not mail_response %}
  110. <h2 class="text-center">Send Us a Message</h2>
  111. <hr>
  112. </center>
  113. <form action="{% url 'contact-form' %}" method="POST" id="email-form">
  114. {% csrf_token %}
  115. <div class="row">
  116. <div class="col-md-6">
  117. <label for="name" class="control-label">Fullname</label>
  118. <input type="text" id="name" name="name" class="form-control rounded-0" required>
  119. </div>
  120. <div class="col-md-6">
  121. <label for="email" class="control-label">Email</label>
  122. <input type="email" id="email" name="email" class="form-control rounded-0" required>
  123. </div>
  124. </div>
  125. <div class="row">
  126. <div class="col-md-12">
  127. <label for="message" class="control-label">Message</label>
  128. <textarea name="message" id="message" rows="10" class="form-control rounded-0" required placeholder="Write your Message here."></textarea>
  129. </div>
  130. </div>
  131. <div class="w-100 d-flex mt-3 justify-content-end">
  132. <div class="col-auto">
  133. <button class="btn btn-primary rounded-0">Send</button>
  134. </div>
  135. </div>
  136. </form>
  137. {% else %}
  138. <h3 class="text-center text-success">Your message has been sent successfully.</h3>
  139. <center>We will respond to your message as soon as we receive your mail. Thanks!</center>
  140. <center><a href="{% url 'contact-form' %}">Send Message Again</a></center>
  141. {% endif %}
  142. </div>
  143. </div>
  144. </div>
  145. </div>
  146. </div>
  147. </div>
  148. </section>
  149. </body>
  150. </html>

The HTML script I provided is using Bootstrap CDNs for the UI design. Make sure that you have an internet connection before running the application.

Run the Project

Run your project by entering the following command in your terminal. Make sure that your current directory should be at your project's root path.

python manage.py runserver

After that, you will like the image below

Next, browse the project in your browser. i.e. http://localhost:8000

Before testing the app. Make sure to follow the Google Account Configuration below.

  • Go to "Google Account". Note: Login your sender's GMail Account.
  • Select "Security" from Left Side Menu.
  • Scroll Down the Page to "Less Secure App Access"
  • Enable "Allow less secure apps"

DEMO VIDEO

Now you can test the project on your end and see if it works as we planned to. If you have encountered any errors, please review the changes you have with the codes I provided. You can also the working source code I created for this tutorial. The download button is located below this article. Make sure to configure the Email Configuration in the settings.py file.

That's the end of this tutorial. I hope you'll find tutorial useful for your future Python Django Projects. Explore more on this website for more Free Source Codes and Tutorials.

Enjoy Coding :)

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
9 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.