Django电子邮件不起作用-smtplib.smtpserverdisconstisconnected:连接意外关闭



我正在使用标准DJANGO/SENDGRID设置来发送电子邮件。这是我的settings.py中的相关字段:

EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'myusername'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 465
EMAIL_USE_SSL = True
DEFAULT_FROM_EMAIL = 'admin@mysite.com'

我正在测试通过执行:

在我的外壳中发送电子邮件
send_mail('test','test','email@email.com',['to@email.com'])

但是,它返回此错误追溯:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/__init__.py", line 62, in send_mail
    return mail.send()
  File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/message.py", line 348, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 104, in send_messages
    new_conn_created = self.open()
  File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 71, in open
    self.connection.login(force_str(self.username), force_str(self.password))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 720, in login
    initial_response_ok=initial_response_ok)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 630, in auth
    (code, resp) = self.docmd("AUTH", mechanism + " " + response)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 420, in docmd
    return self.getreply()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 393, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

知道为什么我会遇到这个错误?

ps:这是我的本地开发服务器

更新了2021

SendGrid现在需要使用API密钥而不是用户名/密码:

截至第4季度,需要两因素身份验证,所有Twilio都需要SendGrid API端点将拒绝新的API请求和SMTP通过基本的用户名和密码制成的配置身份验证。

因此,您需要使用至少Mail Send > Full Access权限创建一个API键,然后像这样调整Django配置:

EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY

示例代码:

settings.py

SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
EMAIL_PORT = 587
EMAIL_USE_TLS = True

utils.py

from django.core.mail import send_mail
send_mail('Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False)

email_port = 465email_use_ssl = true

更改此

email_port = 587email_use_tls = true

您可以检查此链接https://sendgrid.com/docs/for-developers/sending-email/django/

最新更新