Friday, 16 July 2021

*Episode 10* DJANGO ( Sending Email of Django)

 


Sending E-mails


    Django comes with an inbuilt engine for the purpose of sending E-mails. To send the E- mails, you have to import the “smtplib”, similar to what happens in Python. In Django, one has to import the class “django.core.mail”. The parameters for the file “settings.py” also have to be changed. These parameters are given below:


  •  EMAIL_HOST – The smtp server.
  •  EMAIL_HOST_USER – The login credentials for your smtp server.
  •  EMAIL_HOST_PASSWORD – The password credentials for your smtp server.
  •  EMAIL_PORT – The smtp server port.
  •  EMAIL_USE_TLS or _SSL − True if the secure connection is used.

    Consider the view given below, which is a simple demonstration of how one can send an E-mail:


from django.core.mail import send_mail

from django.http import HttpResponse

def sendEmail(request,emailto):

res = send_mail(“hello john”, “Were have you lost?”, “john@mywebsite.com”,

[emailto])

return HttpResponse(‘%s’%res)


   Below are the parameters of the method “send_mail”:

  •  subject – The E-mail subject.
  •  message – The E-mail body.
  •  from_email – The E-mail from.
  •  recipient_list – A list of the receivers’ E-mail addresses.
  •  fail_silently − Boolean, if false, the send_mail will give an exception in case of an error.
  •  auth_user − User login if not set in the “settings.py”.
  •  auth_password − The user password if not set in the “settings.py”.
  •  connection – The E-mail backend.
  •  html_message − If present, our E-mail will be a multipart/alternative.

     The following URL can be used for the purpose of accessing our view:


from django.conf.urls import patterns, url

upatterns = paterns(‘myapplication.views’, url(r’^email/(?P<emailto>

[\w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})/’,

‘sendEmail’ , name = ‘sendEmail’),)


  •  Using “send_mass_mail” to send E-mail :-

     When this method has been used, we will get the number of messages that have been delivered successfully. It is similar to our previous method, but it takes an extra parameter. Consider the code given below:


from django.core.mail import send_mass_mail

from django.http import HttpResponse

def sendEmail(request,emailto):

message1 = (‘subject 1’, ‘message 1’, ‘john@mywebsite.com’, [emailto1])

message2 = (‘subject 2’, ‘message 2’, ‘john@mywebsite.com’, [emailto2])

res = send_ mail((message1, message2), fail_silently = False)

return HttpResponse(‘%s’%res)


    The following URL can be used for accessing the view:


from django.conf.urls import patterns, url

upatterns = paterns(‘myapplication.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})’, ‘sendEmail’ , name = ‘sendEmail’),)


     The following are the parameters for the method:


  •  datatuples − A tuple in which each element will be like “subject, message, from_email, recipient_list”.
  •  fail_silently − Boolean, if set to “false”, send_mail will give an exception in case an error occurs.
  •  auth_user – A user login if it has not been set in “settings.py”.
  •  auth_password – The user password if it has not been set in the “settings.py”.
  •  connection – The E-mail backend.

     The code has been used for sending two E-mails.


     Again, in our code, we have used the “Python smtp debuggingserver” and the following command can be used for launching it:


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


    The above code means that the E-mails that are sent will be printed on the “stdout” and your dummy server is being executed on the port number 1025.


     Sometimes, we might need to send the mails to administrators and managers. In this case, we can use the methods “mail_admins” and “mail_managers” respectively. The settings for these are defined in the file “settings.py”. Let’s assume that the following are the settings for our option:


ADMINS = ((‘john’, ‘john@mywebsite.com’),)

MANAGERS = ((‘joel’, ‘joel@mywebsite.com’),)

from django.core.mail import mail_admins

from django.http import HttpResponse

def AdminsEmail(request):

res = mail_admins(‘my subject’, ‘User Interface is tiresome.’)

return HttpResponse(‘%s’%res)


     With the above code, an E-mail will be send to all of the administrators who are contained in the “ADMINS” section. Consider the code given below:


from django.core.mail import mail_managers

from django.http import HttpResponse

def ManagersEmail(request):

res = mail_managers(‘my subject’, ‘Correct some spelling errors on your site.’)

return HttpResponse(‘%s’%res)


     With the above code, an E-mail will be send to all of the managers defined in the “MANAGERS” section.


     The following are the details of our parameters:


  •  Subject – The E-mail subject.
  •  message – The E-mail body.
  •  fail_silently – A Boolean, if set to “false” “send_mail” will give an exception if an error occurs.
  •  connection – The E-mail backend.
  •  html_message − if it’s present, our e-mail will be a multipart/alternative.

  •  Sending HTML E-mail :-

     Consider the code given below, which demonstrates how this can be done:


from django.core.mail import send_mail

from django.http import HttpResponse

res = send_mail(“hello john”, “where have you lost?”, “john@mywebsite.com”,

[“john@gmail.com”], html_message=”)


     The above code will give out a multipart/alternative E-mail. We want to create a view that will be used for sending an HTML E-mail:


from django.core.mail import EmailMessage

from django.http import HttpResponse

def hTMLEmail(request , emailto):

html_cont = “<strong>Where have you lost?</strong>”

email = EmailMessage(“my subject”, html_cont, “john@mywebsite.com”,

[emailto])


email.content_subtype = “html”

res = email.send()

return HttpResponse(‘%s’%res)


     The following are the parameters of the message:


  •  Subject – The E-mail subject.
  •  message – The E-mail body in HTML.
  •  from_email – The E-mail from.
  •  to − List of our receivers’ E-mail addresses.
  •  bcc − List of the “Bcc” receivers’ of E-mail addresses.
  •  connection – The E-mail backend.

The following is a URL that can be used for accessing our view:


from django.conf.urls import patterns, url

upatterns = paterns(‘myapplication.views’, url(r’^htmlemail/(?P<emailto>

[\w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})/’,

‘hTMLEmail’ , name = ‘hTMLEmail’),)


  •  How to Send Emails with Attachment :-

     For us to do this, we have to use the “attach” method in the object “EmailMesage”. A view for sending an E-mail with an attachment can be implemented as shown below:


from django.core.mail import EmailMessage

from django.http import HttpResponse

def emailWithAttach(request, emailto):

html_cont = “Where have you lost?”

email = EmailMessage(“my subject”, html_content, “john@mywebsite.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 following is a description of the used parameters:


  •  filename − Name of our file to attach.
  •  content − Content of our file to attach.
  •  mimetype − Content mime type of the attachment.

👈Episode 9(D).                                                                                 Episode 11(D)👉
Share This Post
PRINT THIS POST

No comments:

Post a Comment

If you have any doubts. Please let me know.

Featured post

*Episode 1* MCQ for Govt. Job/ Private Job/ MNCs

  Topic:- One Word Substitution 1) Especially skilled in storytelling  Answer:- Raconteur 2) Fear of loneliness Answer:- Eremophobia  3) Usa...