[Django]-How to send a email from a form django

6👍

If you want to send mail then you have to configure this setting in your project’s settings.py file

For example if you want to send email through your gmail account:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "your gmail address"
EMAIL_HOST_PASSWORD = 'your password'
EMAIL_PORT = '587'

And also remember to enable less secure apps in you google account for sending email.
And in the view you can try like this:

if request.method == 'POST' and email and name:
    send_mail(subject, content, settings.EMAIL_HOST_USER, ['kike1996@hotmail.com'], fail_silently=False)
👤arjun

4👍

Essentially this is the line of code that sends an email from djagno.

from django.core.mail import send_mail

send_mail(subject, content, from_email, to_list, fail_silently=False)

The subject and content part are intuitive, then what remains is setting up the from_email and the to_list(which could even be 1 email in a list).

You’ve to define the following variables in your settings file.

EMAIL_USE_TLS = True
EMAIL_HOST = smtp.gmail.com
EMAIL_HOST_USER = user@gsuiteaccount.com
EMAIL_HOST_PASSWORD = password
EMAIL_PORT = 587

Django permits the use of gsuite accounts for sending emails. To set up gsuit, go to your Google Account settings, find Security -> Account permissions -> Access for less secure apps, enable this option.

About this option: https://support.google.com/accounts/answer/6010255
Hope this gets you going.

Leave a comment