使用 Django 和 Sendgrid 的 SMTPSenderRefused 错误

SMTPSenderRefused Error using Django and Sendgrid

几天来,我一直在努力尝试让 SendGrid 从我正在构建的网站上的联系页面发送电子邮件。首先,这是 SMTPServerDisconnected 错误,我想我现在已经修复了这个 SMTPSenderRefused 错误。

settings.py

#Load environment variables from .env file
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')

#Email for contact form
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
DEFAULT_FROM_EMAIL = 'some-email@hotmail.com'
SENDGRID_SANBOX_MODE_IN_DEBUG = False

views.py:

def contact(request: HttpRequest) -> HttpResponse:
    if request.method == "GET":
        form = ContactForm()
    elif request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            name = bleach.clean(form.cleaned_data["name"])
            email = bleach.clean(form.cleaned_data["email"])
            subject = f'Message from {name} about {bleach.clean(form.cleaned_data["subject"])}'
            message = bleach.clean(form.cleaned_data["message"])

            recipients = [settings.DEFAULT_FROM_EMAIL]
            try:
                send_mail(subject, message, email, recipients, fail_silently=False)
            except BadHeaderError:
                return render(request, "contact.html", {"form": form, "success": False})

            form = ContactForm()
            return render(request, "contact.html", {"form": form, "success": True})
    else:
        raise NotImplementedError

    return render(request, "contact.html", {"form": form})

我已经在 fail_silently=Falsefail_silently=True 之间切换了,但是当它为 true 时,电子邮件无论如何都不会发送,所以我暂时将其设置为 false。

最后,这是我得到的回溯:

Environment:


Request Method: POST
Request URL: http://localhost:8000/contact/

Django Version: 4.0
Python Version: 3.9.12
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'Blume_Website.apps.accounts',
 'Blume_Website.apps.contact']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/app/Blume_Website/apps/contact/views.py", line 25, in contact
    send_mail(subject, message, email, recipients, fail_silently=False)
  File "/usr/local/lib/python3.9/site-packages/django/core/mail/__init__.py", line 61, in send_mail
    return mail.send()
  File "/usr/local/lib/python3.9/site-packages/django/core/mail/message.py", line 284, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/usr/local/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 109, in send_messages
    sent = self._send(message)
  File "/usr/local/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 125, in _send
    self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
  File "/usr/local/lib/python3.9/smtplib.py", line 887, in sendmail
    raise SMTPSenderRefused(code, resp, from_addr)

Exception Type: SMTPSenderRefused at /contact/
Exception Value: (550, b'Unauthenticated senders not allowed', 'd@email.com')

“d@email.com”应该是使用联系表的人,我认为这是因为这是一封假电子邮件,但当我尝试使用真实的电子邮件时,也没有用.

我看过无数的堆栈溢出页面,也看过一两个 youtube 视频,但都没有成功。不确定问题出在哪里。感谢您的帮助!

问题是您正在尝试使用尚未验证的 From 地址 - 具体来说,您正在尝试使用 email,这是在表单中提交的电子邮件地址。你不能这样做 - 因为它允许你在未经授权的情况下代表任何人发送邮件。

提供给 send_mailfrom 地址必须是您拥有的地址 verified on Sendgrid,因此您必须:

# Note, 3rd argument has changed
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipients, fail_silently=False)

如果您希望能够回复提交的电子邮件地址,您可以在邮件中设置 reply_to 参数。您不能使用 send_mail 助手来执行此操作 - 您必须使用 EmailMessage class:

from django.core.mail import EmailMessage

email_message = EmailMessage(
    subject,
    message,
    settings.DEFAULT_FROM_EMAIL,
    recipients,
    reply_to=[email],
)
email_message.send()