【问题标题】:530, b'5.7.0 Authentication Required Error when using gmail to send emails through django530, b\'5.7.0 Authentication Required Error when using gmail 通过django发送邮件
【发布时间】:2023-02-13 15:01:17
【问题描述】:

我在 Django 中通过 gmail 发送电子邮件时遇到问题。我已经设置了一个应用程序密码,但我似乎无法通过 Django 发送电子邮件。我的 settings.py 看起来像这样

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_FROM_USER = 'ianis.donica@gmail.com'
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', 'ianis.donica@gmail.com')

我尝试的是更改为 yahoo 和 SendGrid 邮件,但那里发生了同样的问题,只是名称不同。我也尝试更改一些细节,但这不应该是问题所在吗?但是我似乎无法在任何地方发送电子邮件。如果有人能帮助我,我将不胜感激

我也启用了 IMAP

【问题讨论】:

  • 请编辑您的代码并包含您的 EmailMessage 方法
  • 这是来自 django.core.mail 的 django 方法,名为 EmailMessage,代码的第一部分在 settings.py 中,第二部分在 views.py 中,一旦创建新用户就会被调用在数据库中,如果需要,here 是完整的 views.py

标签: python django email smtp gmail


【解决方案1】:

问题出在我使用 EMAIL_FROM_USER 而不是 EMAIL_HOST_USER,所以我需要将代码更改为此

settings.py

...
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'ianis.donica@gmail.com'
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 不会尝试进行身份验证

【讨论】:

    猜你喜欢
    • 2023-01-29
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 2015-10-18
    • 2020-08-20
    • 1970-01-01
    • 2020-05-13
    相关资源
    最近更新 更多