Django Mail Setup

Sending email using Django in a very easy way and less configuration. In this series, I am going to show you how to send an email using Django.

Django provides built-in mail library django.core.mail to send an email.

We need to make some changes in Gmail account for security reason Google does not allow direct access(Log in) by any application. check screenshot how to Less secure app access.

https://myaccount.google.com/lesssecureapps

After that follow this URL that is an additional security check to verify the make security constraint.

https://accounts.google.com/b/0/DisplayUnlockCaptcha

Django Configuration
Provide the SMTP and Gmail account details into the settings.py file. For example

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '***********@'

Import Mail Library

from django.core.mail import send_mail

Now, write a view function that uses built-in mail function to send mail.
See the example

Django Email Example

This example contains the following files.

// views.py

from django.http import HttpResponse
from mysite import settings
from django.core.mail import send_mail

def mail(request):
    subject = "Real programmer contact"
    msg = "Congratulations for your success"
    to = "[email protected]"
    res = send_mail(subject, msg, settings.EMAIL_HOST_USER, [to])
    if(res == 1):
        msg = "Mail Sent"
    else:
        msg = "Mail could not sent"
    return HttpResponse(msg)

Put the following URL into urls.py file.

path(‘mail’,views.mail)

python manage.py runserver

Hit on url

http://127.0.0.1:8000/mail

check your email

Leave a Comment