English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Django Email Sending

   Django provides a ready-to-use, easy-to-use lightweight engine for sending emails. Similar to Python, you need to import smtplib. In Django, you only need to import django.core.mail. To send an email, edit the project's settings.py file and set the following options −

EMAIL_HOST − SMTP server EMAIL_HOST_USER − Log in credentials for SMTP server     EMAIL_HOST_PASSWORD − SMTP server password credentials     EMAIL_PORT − SMTP server port     EMAIL_USE_TLS or   _SSL − If set to True, it is a secure connection.    

Send a simple email

Let's create a "sendSimpleEmail" view to send a simple email.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.core.mail import send_mail
 from django.http import HttpResponse
 def sendSimpleEmail(request, emailto):
    res = send_mail("hello paul", "comment tu vas?", "xxx@w"3codebox.com", [emailto])
    return HttpResponse('%s'%res)

Here are the details of send_mail parameters −

subject − E-mail subject     message − E-mail content     from_email − E-mail sender     recipient_list − List of recipient's email addresses     fail_silently − Boolean, if it is false, send_mail will raise an exception when an error occurs     auth_user − User login, if not set in settings.py     auth_password − User password, if not set in settings.py     connection − E-mail backend     html_message − (Django1.7New feature added in Chinese, if any, the email will be multipart/alternative.    

Let's access the URL of our view -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, url
 urlpatterns = patterns('myapp.views', url(r'^simpleemail/(?P<emailto>
    [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/', 
    )

So, when accessing /myapp/simpleemail/  [email protected]/ when you send emails with send_mass_mail, you will enter the following page −  

Sending multiple emails with send_mass_mail

The method returns the number of messages successfully transmitted. It is similar to send_mail but requires an additional parameter; datatuple, the sendMassEmail view of our application is −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.core.mail import send_mass_mail
 from django.http import HttpResponse
 def sendMassEmail(request, emailto):
    msg1 = ('subject 1', 'message 1', '[email protected]', [emailto1])
    msg2 = ('subject 2', 'message 2', '[email protected]', [emailto2])
    res = send_mass_mail((msg1, msg2), fail_silently = False)
    return HttpResponse('%s'%res)

Let's create the URL of our view to access −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, url
 urlpatterns = patterns('myapp.views', url(r'^massEmail/(?P<emailto1>
    [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/(?P<emailto2>
    [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4)

When we access /myapp/massemail/[email protected]/[email protected]/, we get −  

The detailed parameters of the send_mass_mail are as follows −

datatuples    Tuple, each element is like (subject, message, from_email, recipient_list)     fail_silently − Boolean, if false, send_mail will raise an exception when an error occurs     auth_user − User login, if not set in settings.py     auth_password − User password, if not set in settings.py     connection − E-mail backend    

As you can see in the above image, two messages have been successfully sent.

Note - In this example, we use Python's smtpd debuggingserver, which can be started with the following command −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
$python -m smtpd -n -c DebuggingServer localhost:1025

This means that all sent emails will be printed in stdout and the virtual server running on localhost:1025.

Send emails to administrators and managers using the mail_admins and mail_managers methods

These methods send emails to website administrators as defined by the ADMINS option in the settings.py file, and website administrators are defined in the MANAGERS item in the settings.py file. Assume that our ADMINS and MANAGERS look like this-

ADMINS   = (('polo', '[email protected]'),)

MANAGERS = (('popoli', '[email protected]'),)

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.core.mail import mail_admins
 from django.http import HttpResponse
 def sendAdminsEmail(request):
    res = mail_admins('my subject', 'site is going down.')
    return HttpResponse('%s'%res)

The above code will send an email to each administrator defined in the ADMINS section.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.core.mail import mail_managers
 from django.http import HttpResponse
 def sendManagersEmail(request):
    res = mail_managers('my subject' 2', 'Change date on the site.')
    return HttpResponse('%s'%res)

The above code will send an email to each administrator defined in the MANAGERS section.

Parameter details −

Subject − E-mail subject.     message − E-mail subject.     fail_silently − Boolean, if false, send_mail will raise an exception when an error occurs     connection − E-mail backend.     html_message − (Django1.7New feature added in Chinese, if any, the email will be multipart/alternative.    

send HTML E-mail

in Django>=1.7Sending HTML messages is as simple -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.core.mail import send_mail
 from django.http import HttpResponse
    res = send_mail("hello paul", "comment tu vas?", "[email protected]", 
          ["[email protected]"], html_message=")

This will produce a multipart/alternative email.

but for Django<1.7 Sending HTML emails is done through the django.core.mail.mailMessage class, then calling the 'send' object−

Let's create a 'sendHTMLEmail' view to send HTML emails.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.core.mail import EmailMessage
 from django.http import HttpResponse
 def sendHTMLEmail(request, emailto):
    html_content = "<strong>Comment tu vas?</strong>"
    email = EmailMessage("my subject", html_content, "[email protected]", [emailto])
    email.content_subtype = "html"
    res = email.send()
    return HttpResponse('%s'%res)

Email message creation class with detailed information of parameters −

Subject − E-mail subject.     message − E-mail in HTML body.     from_email − E-mail sender.     to − The email address list of the recipient.     bcc − The email address list of the 'BCC' recipient.     connection − E-mail backend.    

Let's create a URL for the view access −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, url
 urlpatterns = patterns('myapp.views', url(r'^htmlemail/(?P<emailto>
    [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/', 
    'sendHTMLEmail', name = 'sendHTMLEmail'),)

When we access /myapp/htmlemail/[email protected], will receive the following content −  

Send an email with an attachment

This is done by using the 'attach' method on the EmailMessage object.

A view to send an email with the following attachment −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.core.mail import EmailMessage
 from django.http import HttpResponse
 def sendEmailWithAttach(request, emailto):
    html_content = "Comment tu vas?"
    email = EmailMessage("my subject", html_content, "[email protected]", emailto)
    email.content_subtype = "html"
    fd = open('manage.py', 'r')
    email.attach('manage.py', fd.read(), 'text/plain')
    res = email.send()
    return HttpResponse('%s'%res)

Detailed parameters in the attachment −

filename − The name of the attached file     content − The content of the file, attached.     mimetype − Attachment content MIME type.