使用Django EmailBackend发送电子邮件时出现问题
我不知道我的代码有什么问题.我正在尝试使用 django.core.mail.backends.smtp.EmailBackend 使用send_mail,但无法正常工作.我的gmail帐户的安全级别已解锁,并且python中的消息看起来像发送了电子邮件.但是电子邮件没有到达我的电子邮件帐户.贝娄是我正在使用的代码.
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
在文件顶部
...
# send email
from django.core.mail import send_mail
...
在请求页面
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
-------------------------------------------------------------------------------
我注意到您正在使用Gmail发送电子邮件.在这种情况下,您可以允许对Gmail帐户的安全性降低.请按照以下步骤操作:
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.转到 https://myaccount.google.com/security (登录Google后)
2.向下滚动到不安全的应用访问权限"部分,然后单击打开访问权限"
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
现在Django应该可以发送电子邮件了.如果电子邮件被拒绝,则您连接的Gmail应该会向您发送失败通知电子邮件.
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.