Updated May 3, 2023
Introduction to Django Mail
Apart from the SMTP mail connectivity offered by Python, Django also provides the django.core.mail library for handling email requests. Any email-oriented process can be handled very flexibly by this library. We can use this library to send emails to external users, website admins, and website managers; emails with attachments and even emails to a bulk set of mass users can be triggered. Adjusting the email delivery process in Django-based frameworks can easily meet individual needs and significantly speed up the process.
How does Django Mail work?
Given below shows how Django Mail works:
1. To connect the email setup to Django, the below-listed email configurations should be in the SETTINGS.PY file.
- EMAIL_HOST − SMTP server.
- EMAIL_HOST_USER − SMTP server login credentials.
- EMAIL_HOST_PASSWORD − SMTP server password credentials
- EMAIL_PORT − port of SMTP server.
- EMAIL_USE_TLS or _SSL − True if secure connection.
Code:
#---------- EMAIL HANDELING ----------#
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '*********'
EMAIL_USE_TLS = True
a. EMAIL_BACKEND
The email backend protocol used is referred to in the EMAIL_BACKEND variable. Some of the protocols are SMTP, SMTPS, IMAP, etc. By default, Django utilizes the SMTP protocol. Here, we explicitly mention the SMTP representation through the variable ‘django.core.mail.backends.smtp.EmailBackend’.
b. EMAIL_HOST
The email host refers to the email provider expected to reach; it represents the SMTP hostname of that email provider.
Example: smtp.mail.yahoo.com
c. EMAIL_PORT
The email port refers to the email provider’s port which is opened for SMTP connectivity.
Example: for yahoo the port number is 465
d. EMAIL_USER
Please provide the username for the email account that we need to connect.
Example: [email protected]
e. EMAIL_PASSWORD
This represents the password of the corresponding email account.
f. EMAIL_USE_TLS
This parameter is used to mention whether TLS secure connection needs to be turned on or not.
2. The next critical step is using django.core.mail.
The django.core.mail library has four methods for handling emails.
a. send_mail()
Syntax:
send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None,connection=None, html_message=None)
Description:
This method sends the email and posts the number of messages delivered.
b. send_mass_mail()
Syntax:
send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None)
Description:
Sends mail to a wide set of people; the data tuple combines the below elements.
(subject, message, from_email, recipient_list)
c. mail_admins()
Syntax:
mail_admins(subject, message, fail_silently=False, connection=None, html_message=None)
Description:
Sends mail to side admins as the admin names are declared in the ADMIN settings.
d. mail_managers()
Syntax:
mail_managers(subject, message, fail_silently=False, connection=None, html_message=None)
Description:
Sends mail to side managers as the Manager names are declared in the MANAGER settings.
Example:
Code:
send_mail(
'Subject',
'Message.',
'[email protected]',
['[email protected]', '[email protected]'],
)
Code:
python -m smtpd -n -c DebuggingServer 127.0.0.1:8001
Output:
Examples of Django Mail
Given below are the examples mentioned :
Example #1
The email is captured in the temporary SMTP server in the first example. The server is set up to hear at port 8001. Also, the Django server localhost id (127.0.0.1) is set as the hostname here.
a. Make the email configurations in the SETTINGS.py file.
SETTINGS.py
#---------- EMAIL HANDELING ----------#
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = '127.0.0.1'
EMAIL_PORT = 8001
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = True
b. Set the view for email processing. The send_email() method triggers the email by tagging it with three fields captured from the front-end webpage through the form.
Views.py
Code:
def email_sending(request):
email = emailform()
if request.method == 'POST':
email_id = request.POST['email']
email_subject = request.POST['email_subject']
email_message = request.POST['email_message']
res = send_mail(email_subject,email_message,'[email protected]',[email_id],fail_silently = False)
return HttpResponse('%s'%res)
return render(request, 'emailpage.html',{"email":email})
forms.py
Code:
from django import forms
class emailform(forms.Form):
email = forms.EmailField()
email_subject = forms.CharField()
email_message = forms.CharField(max_length = 2000)
c. Formulate the template for preparing the webpage.
Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
{% load static %}
<link href="{% static 'admin/css/font.css' %}" rel="stylesheet">
<style>
body {
background-image: url("{% static 'admin/img/background.jpg' %}");
background-color: #acccbb;
}
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center;
font-family: "Comic Sans MS", cursive, sans-serif;
font-size: 14px;
letter-spacing: 2px;
word-spacing: 1.8px;
text-align: left;
color: #02071C;
font-weight: 200;
text-decoration: none;
font-style: normal;
font-variant: normal;
text-transform: capitalize;
}
</style>
</head>
<body>
<h1> <u> DJANGO HANDELING EMAILS </u> </h1>
<div class="myDiv" style = "max-width:470px;">
<form method = 'POST'>
{{ email.as_p }}
{% csrf_token %}
<input type="submit" class="btn btn-primary" value="submit" style="text-align:center">
</form>
</div>
</body>
</html>
d. Kickstart the email server in debugging mode. Once you start it, the server will be ready to receive any messages posted to its port.
Output:
Webpage:
Server port:
Example #2
The second example triggers the email using a valid mail account.
a. Make the email configurations in the SETTINGS.py file.
SETTINGS.py
Code:
#---------- EMAIL HANDELING ----------#
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '*********'
EMAIL_USE_TLS = True
b. Formulate the template for preparing the webpage.
Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
{% load static %}
<link href="{% static 'admin/css/font.css' %}" rel="stylesheet">
<style>
body {
background-image: url("{% static 'admin/img/background.jpg' %}");
background-color: #acccbb;
}
.myDiv {
border: 5px outset red;
background-color: lightblue;
text-align: center;
font-family: "Comic Sans MS", cursive, sans-serif;
font-size: 12px;
letter-spacing: 1px;
word-spacing: 1.7px;
text-align: left;
color: #02061C;
font-weight: 100;
text-decoration: none;
font-style: normal;
font-variant: normal;
}
</style>
</head>
<body>
<h1> <u> DJANGO HANDELING EMAILS </u> </h1>
<div class="myDiv" style = "max-width:470px;">
<form method = 'POST'>
{{ email.as_p }}
{% csrf_token %}
<input type="submit" class="btn btn-primary" value="submit" style="text-align:center">
</form>
</div>
</body>
</html>
Output:
Webpage:
Email snaps:
Conclusion
The above article provides clear explanations and practical examples on how to set up and trigger real-time email SMTP through the debugging process.
Recommended Articles
We hope that this EDUCBA information on “Django Mail” was beneficial to you. You can view EDUCBA’s recommended articles for more information.