通过 django celery 发送电子邮件时出现 Gmail 身份验证错误

Gmail authentication error when sending email via django celery

TL;DR:尝试使用 Django 应用程序中的 Celery/RabbitMQ 任务发送电子邮件时,我从 Gmail 收到 SMTPAuthenticationError,尽管传入的凭据是正确的。在没有 Celery 的情况下正常发送电子邮件时不会发生这种情况。

嗨,

我正在尝试在我的 Django 应用程序中使用 Celery/RabbitMQ 向用户异步发送电子邮件。我有以下代码发送电子邮件:

from grad.celery import app
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from grad import gradbase
from time import sleep
from grad import settings

@app.task
def send_transaction_email(student_data, student_email):
    html_email = get_template('grad/student_email.html')
    context = Context({
        'name': student_data['name'],
        'university': student_data['university'],
        'data': student_data,
        'shorturl':  gradbase.encode_graduation_data(student_data)
    })
    msg = EmailMultiAlternatives('Subject Here',
                             'Message Here',
                             'myrealemailaddress@gmail.com',
                             [student_email])
    msg.attach_alternative(html_email.render(context), "text/html")
    msg.send()

当我正常调用方法时:

tasks.send_transaction_email(entry, stud_email)

电子邮件发送正常,但如果我像这样将调用委托给 Celery 任务:

tasks.send_transaction_email.delay(entry, stud_email)

我得到以下跟踪:

Traceback (most recent call last):
File "/Users/albydeca/Gradcoin/venv/lib/python2.7/site-        packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "/Users/albydeca/Gradcoin/venv/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
return self.run(*args, **kwargs)
File "/Users/albydeca/Gradcoin/grad/tasks.py", line 27, in   send_transaction_email
msg.send()
File "/Users/albydeca/Gradcoin/venv/lib/python2.7/site-packages/django/core/mail/message.py", line 303, in send
return self.get_connection(fail_silently).send_messages([self])
File "/Users/albydeca/Gradcoin/venv/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages
new_conn_created = self.open()
File "/Users/albydeca/Gradcoin/venv/lib/python2.7/site- packages/django/core/mail/backends/smtp.py", line 69, in open
self.connection.login(self.username, self.password)
File   "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 622, in login
raise SMTPAuthenticationError(code, resp)
SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn    more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials q8sm53748398wjj.7 - gsmtp')

基本上 Gmail 无法识别凭据,尽管当我在导致崩溃的那一行之前的两行上逐字打印它们时,它们是正确的。

有人可以帮助我吗?

尝试在此处设置一个应用密码 https://security.google.com/settings/security/apppasswords 并将其用作 STMP 设置中的密码。