我在 Django 中通过 gmail 发送电子邮件时遇到问题。我已经设置了应用程序密码,但似乎无法通过 Django 发送电子邮件。我的 settings.py 看起来像这样
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_FROM_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'my app password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
据我所知,这不是 gmail 特有的问题,因为我在 yahoo mail 和 Sendgrid 中都遇到过同样的问题,负责发送电子邮件的功能如下
def send_activation_email(user, request):
current_site = get_current_site(request)
email_subject = "Activation Email"
context = {"user": user,
"domain": current_site,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': generate_token.make_token(user)
}
email_body = render_to_string('email/activate.html',context)
email = EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email])
email.send()
完整的错误消息是这样的
SMTPSenderRefused at /register/
(530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError g9-20020a170906394900b00872a726783dsm9975622eje.217 - gsmtp', '[email protected]')
我尝试更改为 yahoo 和 SendGrid 邮件,但那里出现了相同的问题,只是名称不同。我也尝试过更改一些细节,但这不应该是问题吗?但我似乎无法在任何地方发送电子邮件。如果有人可以帮助我,我将非常感激
我也启用了 IMAP
问题出在我使用 EMAIL_FROM_USER 而不是 EMAIL_HOST_USER,所以我需要将代码更改为这样
settings.py
...
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'my app password'
...
views.py
...
email = EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_HOST_USER, to=[user.email])
...
这是因为如果没有 EMAIL_HOST_USER,Django 将不会尝试进行身份验证