Saturday, October 2, 2021

thumbnail

How to Send Email in Django

 


How to Send Email in Django


In a web application we need to send email for many purposes like for email verification during

registration, for resetting password, for integrating notifications of events etc. It depends on the type

of the web application. To send email from a Django application we have to make sure the email can

be logged in by the application. For email there are also some settings which need to be changed for it.

Here the whole procedure has been shown in a few steps.


Step 1: Email Configuration

Email address, password, port etc. has to be specified inside settings.py file. 


settings.py


EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_PORT = 587

EMAIL_USE_TLS = True

EMAIL_HOST_USER = 'user@gmail.com'

EMAIL_HOST_PASSWORD = 'password'



Here EMAIL_BACKEND will be the same if a custom backend is not used. ‘smtp.gmail.com’ is for

Gmail. 587 is the port number for Gmail. Your email id and password in ‘EMAIL_HOST_USER’ and

‘EMAIL_HOST_PASSWORD’ respectively.


Step 2: Setting up Gmail Account

Here the application will login to the email and then the email will be sent. But in Gmail it can be

blocked. To avoid it, two things needed:


  1. Turn off the two factor verification inside the settings of the Gmail account.

  2. Turn On the less secure app access. To do this go to the

‘Manage your Google account’>security. Now turn on the less secure app access.

    

    



The default setting is 'Off'. You have to turn in 'On'. After turning it one check the email. A confirmation email will be there to check whether you have done it or not. Ensure it is you. 

Step 3: Write the code to send email when required in views.py


from django.core.mail import send_mail

def send(request):

send_mail(

            ‘Email Subject here’,

            ‘Email content’,

            settings.EMAIL_HOST_USER,

            [‘emailto@gmail.com’],

            fail_silently=False)


Here the email address where the email to be sent should be in a list. The email subject can be written

in a variable and then used. Email content can be taken from a text or html file as well. 


This is the full setup and a very easy procedure to send email in Django. If there is any error then let

us know in the comment. 

Happy Coding…!


Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments