Django Sending E-mails - How to Send Email in a Django App | W3Schools

Django enables the user to send an e-mail by using its all time ready and easy to use light engine. To make this feature happen, you are required to import smtplib as done in the case of Python. Now, to be able to send an e-mail, you need to make a few changes in your settings.py file where you will be setting the below provided options –

  • EMAIL_HOST – It is the SMTP (Simple Mail Transfer Protocol) server.
  • EMAIL_HOST_USER – This option carries the login credentials of the user for the SMTP server.
  • EMAIL_HOST_PASSWORD – This option stores the password for the corresponding user for the SMTP server.
  • EMAIL_PORT – This is the SMTP server port.
  • EMAIL_USE_TLS or EMAIL_USE_SSL – If the connection is secure in nature then the value for this option will be true.

How to Send A Simple E-mail?
In this section, we will help you to understand how to send a simple email by using the sendSimpleEmail view.

from django.core.mail import send_mail
from django.http import HttpResponse\
def sendSimpleEmail(request,emailto):
   res = send_mail(“hello paul”, “comment tu vas?”, “paul@polo.com”, [emailto])
   return HttpResponse(‘%s’%res)

The details of the parameters used by the send_mail are given below:

  • subject – This parameter carries the subject of the email.
  • message – The main body of the mail is carried by the message parameter.
  • from_email – The email address of the sender is contained by the from_email parameter.
  • recipient_list – All the email addresses of the recipients come under this parameter.
  • fail_silently – This parameter returns the bool value (true or false). The false value of the send_mail represents the raise of an exception in case of the occurrence of an error.
  • auth_user – This parameter needs to be used if the user login credentials are not set in the settings.py file.
  • auth_password – This parameter needs to be used whenever the user password is not set in the settings.py file.
  • connection – The connection parameter represents the backend of the email.
  • html_message – This is a new parameter found in Django 1.7. If this parameter is present, then the email can be of multipart or can be treated as an alternative.

Now, it’s time to create an associated URL to this newly created view as provided below:

from django.conf.urls import patterns, url
urlpatterns = paterns(‘myapp.views’, url(r’^simpleemail/(?P<emailto>
   [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/’,
   ‘sendSimpleEmail’ , name = ‘sendSimpleEmail’),)

After you type in the given URL: http://127.0.0.1:8000/myapp/simplemail/polo@gmail.com, you will land up on the following screen.

How to Send Multiple E-mails Using send_mass_mail() Method?
The send_mass_mail() method is capable of sending multiple mails at once. On delivery of all the mails, the method returns the number of successful deliveries. This method works similar to the send_mail() method. The only difference is that the send_mail() method accepts an extra argument or parameter which is datatuple. The following section of code represents the sendMassEmail view.

from django.core.mail import send_mass_mail
from django.http import HttpResponse
def sendMassEmail(request,emailto):
   msg1 = (‘subject 1’, ‘message 1’, ‘polo@polo.com’, [emailto1])
   msg2 = (‘subject 2’, ‘message 2’, ‘polo@polo.com’, [emailto2])
   res = send_mass_mail((msg1, msg2), fail_silently = False)
   return HttpResponse(‘%s’%res)

The other section of code will allow a URL to access the newly created view.

from django.conf.urls import patterns, url
urlpatterns = paterns(‘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})’, ‘sendMassEmail’ , name = ‘sendMassEmail’),)

Now, type in the given URL: http://127.0.0.1:8000/myapp/massemail/polo@gmail.com/sorex@gmail.com/ in the web browser to get to the desired web page.

The parameters of the send_mass_mail() method are provided below –

  • datatuples – A tuple carries several elements which can be subject, message, from_email, and recipient_list.
  • fail_silently – This parameter returns the bool value. If send_mail parameter returns the false value, then the parameter will raise an exception in the case of occurrence of an error.
  • auth_user – The auth_user parameter gets used whenever the user login is not set in the settings.py file.
  • auth_password – The parameter gets used when the user password is not set in the settings.py file.
  • connection – The connection parameter contains the email backend.

The above screen clearly shows that 2 e-mails have been sent successfully by using the send_mass_mail() method.

Note: In here, we are using Python SMTP DebuggingServer which can be launched by using the following command –

$python -m smtpd -n -c DebuggingServer localhost:1025

This command will display all the sent emails on the stdout. And to access the dummy server, you need to enter the localhost:1025 in the URL section.

In case, you want to send emails to admins and managers then you are required to make use of mail_admins() and mail_managers() methods respectively.

The mail_admins() method lets the developer send emails to site administrators. The definition of this method is defined under the ADMINS option of the settings.py file. Another method which is mail_managers() is used to send emails to site managers. Its definition is also defined in settings.py file under the MANAGERS option. To understand this more clearly, you can assume that the ADMINS and MANAGERS option can have values like the following:

ADMINS = ((‘polo’, ‘polo@polo.com’),)
MANAGERS = ((‘popoli’, ‘popoli@polo.com’),)

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 the email to the site administrator by using the mail_admins() method.

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 the email to the site manager by using the mail_managers() method.

The details of the below provided parameters are:

  • subject – The parameter carries the subject of the email.
  • message – The message parameter contains the body of the email.
  • fail_silently – This parameter accepts a bool value, which could be either true or false. If the value of the send_mail() method is false then an exception will be raised after the occurrence of an error.
  • connection – This parameter contains the details of the backend of the email.
  • html_message – This feature is present in Django 1.7. This parameter lets your email to be distributed in multipart or you can use it as an alternative.

How to Send HTML E-mail?
Well, sending an HTML email is quite easy in Django 1.7 as compared to its earlier versions. The below section of code will help you to understand this:

from django.core.mail import send_mail
from django.http import HttpResponse
   res = send_mail(“hello paul”, “comment tu vas?”, “paul@polo.com”,
         [“polo@gmail.com”], html_message=”)

The code will let you send a multipart or alternative email.

In the earlier versions of Django, to send an HTML email, you are required to use django.core.mail.EmailMessage class. After which, you need to call the send() method on the object as shown in the below section of code:

For this, you first need to create a sendHTMLEmail view. This view will let you send an HTML message.

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, “paul@polo.com”, [emailto])
   email.content_subtype = “html”
   res = email.send()
   return HttpResponse(‘%s’%res)

The details of the parameters used in the EmailMessage class creation are given below:

  • subject – The subject parameter carries the subject of the HTML message.
  • message – This parameter contains the main body of your HTML email.
  • from_email – The parameter contains the email address of the sender.
  • to – The list of recipients’ email addresses is stored under the ‘to’ parameter of the EmailMessage class.
  • bcc – The email addresses which are put under the bcc section are carried under this parameter.
  • connection – The connection parameter carries the backend of your HTML email.

Now, it is important that you create a URL to access the newly created sendHTMLEmail view.

from django.conf.urls import patterns, url
urlpatterns = paterns(‘myapp.views’, url(r’^htmlemail/(?P<emailto>
   [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/’,
   ‘sendHTMLEmail’ , name = ‘sendHTMLEmail’),)

Type in the given URL: http://127.0.0.1:8000/myapp/htmlemail/polo@gmail.com in the web browser so that you will land on to the below provided web page:

How to Send an Email with an Attachment?
To send an email with an attachment, you are required to make use of ‘attach’ method which falls under the EmailMessage object.

The following section of code is the view which is used to send an email with an attachment.

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, “paul@polo.com”, 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)

The arguments which are used in the above view are explained below:

  • filename – This parameter contains the name of the file to be attached to the email.
  • content – The content of the file to be attached is stored under the ‘content’ argument.
  • mimetype – The mime type of the content of the attachment is placed under this parameter.