'Problems to send email using Django EmailBackend
I don´t know what is wrong in my code. I´m trying to use send_mail using django.core.mail.backends.smtp.EmailBackend but is not working. The security level of my gmail account is unlocked and the message in python looks like sent the email message. But the email didn´t arrive in my email account. Bellow are the codes that I´m using.
settings.py
# Email configuration
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '<my_email>@gmail.com'
EMAIL_HOST_PASSWORD = '<my_password>'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
views.py
In the top of file
...
# send email
from django.core.mail import send_mail
...
In the request page
def contact_us(request):
if request.method == 'POST':
form = ContactFormEN(request.POST)
if form.is_valid():
sender_name = form.cleaned_data['name']
sender_email = form.cleaned_data['email']
message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message'])
send_mail('New Message from site', message, sender_email, ['<my_email>@gmail.com'], fail_silently=False)
return render(request, 'contact_us.html')
After run the code the console shows the follow message
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: New Message from site
From: <from_email>@gmail.com
To: <my_email>@gmail.com
Date: Mon, 15 Mar 2021 23:01:50 -0000
Message-ID:
<161584931042.10464.14254641113919007176@my_machine_name>
Name has sent you a new message:
Test message
-------------------------------------------------------------------------------
Solution 1:[1]
I noticed you're using Gmail to send the emails. In that case, you have allow Less Secured Access to your gmail account. Follow these steps to do so:
1. Go to https://myaccount.google.com/security (after you login to Google)
2. Scroll down to Less secure app access section and click TURN ON access
Now Django should be able to send emails. If an email is rejected, the Gmail you connected to should send you a failure notice email.
Solution 2:[2]
As docs says django.core.mail.backends.console.EmailBackend should be used in a development environment as this backend will never send a real email.
In the django settings you must write:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
Solution 3:[3]
Google claims that on May 5, 2022, they will shut down all "less secure apps": https://support.google.com/accounts/answer/6010255?hl=en.
You have to configure and secure your Google account and then you can "Use an App Password" in order to use django.core.mail.backends.smtp.EmailBackend
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | vladthelad |
Solution 2 | Tiki |
Solution 3 | richardec |