django-email

How to send emails using gmail SMTP server with Django??

Mayank Porwal
2 min readAug 9, 2019

Here i will show you how to send a mail to admin when someone enquiry for any product from your website/web application.

I will discuss the simplest way to send email.

Lets Start

Basically you need to do two things:

1- First we configure mail server in settings.py file and

2- Define views function in views.py file

Configure Mail Function

Here is my settings.py:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'your_mail@gmail.com'
EMAIL_HOST_PASSWORD = 'your_password'
EMAIL_USE_TLS = True

Here we elaborate one by one:

EMAIL_BACKEND: This specifies the django backend and this will work with email host server(EMAIL_HOST).
EMAIL_HOST: This is linked with gmail smtp or you can link with another smtp server like: yahoo etc.
EMAIL_USE_TLS: This tells the django what secure protocol should be used to connect to the server. Currently we have used TLS but you can also use SSL by replacing EMAIL_USE_SSL and set them as True. (Note: You can not use both of them at once.)
EMAIL_PORT: If you using TLS, port value should be 587 but if you are using SSL the port value should be 465.
EMAIL_HOST_USER: Set you working email address.
EMAIL_HOST_PASSWORD: Set your password.

Define view function

To send email you should have to import some settings into views.py file.

from django.core.mail import send_mail
from django.conf import settings

I have import send_mail and settings.

Django use send_mail() function for send mail to users. It’s takes some parameter like: subject, message, from_email, to_emails(should be a list or tuple).

The simplest function for sending the email we can write for sending the mail using gmail SMTP in views.py file.

from_email = settings.EMAIL_HOST_USER
send_mail(
'Subject Line',
'Message',
'from_email',
'to_email',
fail_silently=False,
)

Special Notes:

1- If you are using gmail account with two-factor authentication, create App password using the given link.

--

--