我正在使用标准Django/SendGrid setup发送电子邮件。这是我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'
我正在测试通过执行以下命令在我的shell中发送电子邮件:
send_mail('test','test','email@email.com',['to@email.com'])
然而,它返回此错误Traceback:
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:这是我的本地开发服务器
答案 0 :(得分:2)
Sendgrid 现在需要使用 API Key 而不是用户名/密码:
<块引用>自 2020 年第四季度起需要双重身份验证,所有 Twilio SendGrid API 端点将拒绝新的 API 请求和 SMTP 通过 Basic 使用用户名和密码进行配置 身份验证。
因此,您需要 create an API Key 至少拥有 Mail Send > Full Access
权限,然后像这样调整您的 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)
答案 1 :(得分:0)
EMAIL_PORT = 465 EMAIL_USE_SSL = True
更改此
EMAIL_PORT = 587 EMAIL_USE_TLS = True
,您可以检查此链接 https://sendgrid.com/docs/for-developers/sending-email/django/