我写了这段代码 的 settings.py
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=587
EMAIL_HOST_USER = 'myemailhere@gmail.com'
EMAIL_HOST_PASSWORD = '**********'
DEFAULT_FROM_EMAIL = 'myemailhere@gmail.com'
EMAIL_USE_TLS = True
views.py
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email ['myemailhere@gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "email.html", {'form': form})
def success(request):
email = EmailMessage('Hello', 'how are you?', to=['myemailhere@gmail.com'])
email.send()
send_mail('Test mail', 'This is a test', 'myemailhere@gmail.com' ['myemailhere@gmail.com'], fail_silently=False)
return HttpResponse('Success! Thank you for your message.')
在成功(请求)中,我添加了一些冗余代码,尝试以不同的方式发送邮件,以检查其他方法是否正常工作。它都不起作用。谁能告诉我为什么?我有点困惑。密码是正确的,我允许gmail的安全性较低的应用程序。这个程序不会抛出任何错误。如果电子邮件(请求)告知已成功发送邮件,则调用成功页面。我使用的是django 1.11和Python 2.7 谢谢你提前:))
答案 0 :(得分:2)
控制台后端无法发送真实的电子邮件:
控制台后端只是编写将发送到标准输出的电子邮件,而不是发送真实的电子邮件。默认情况下,控制台后端会写入stdout。
https://docs.djangoproject.com/en/1.11/topics/email/#console-backend
根据您设置日志记录的方式,使用send_mail
发送的电子邮件应该位于日志文件中的某个位置(如果您没有记录stdout,则不会。)
您必须像这样修改settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
答案 1 :(得分:0)
当您将值传递到send_mail
函数时,您忘记使用逗号,首先是from_email
之后:
send_mail(subject, message, from_email, ['myemailhere@gmail.com'])
和'myemailhere@gmail.com'
之后的第二个
send_mail('Test mail', 'This is a test', 'myemailhere@gmail.com', ['myemailhere@gmail.com'], fail_silently=False)
此外,您必须从 settings.py 文件中删除该行EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
。