Zor*_*gan 5 python email django sendgrid
我使用标准的Django/SendGrid 设置来发送电子邮件。这是 my 中的相关字段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'
Run Code Online (Sandbox Code Playgroud)
我正在测试通过执行以下命令在我的 shell 中发送电子邮件:
send_mail('test','test','email@email.com',['to@email.com'])
Run Code Online (Sandbox Code Playgroud)
但是,它返回此错误回溯:
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
Run Code Online (Sandbox Code Playgroud)
知道为什么我会收到此错误吗?
PS:这是我的本地开发服务器
Sendgrid 现在需要使用API 密钥而不是用户名/密码:
自 2020 年第 4 季度起,需要进行双因素身份验证,所有 Twilio SendGrid API 端点将拒绝新的 API 请求以及通过基本身份验证使用用户名和密码进行的 SMTP 配置。
因此,您需要创建一个至少具有权限的API 密钥Mail Send > Full Access
,然后像这样调整您的 Django 配置:
EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
Run Code Online (Sandbox Code Playgroud)
示例代码:
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
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
小智 4
EMAIL_PORT = 465 EMAIL_USE_SSL = True
改变这个
EMAIL_PORT = 587 EMAIL_USE_TLS = True
您可以检查此链接 https://sendgrid.com/docs/for-developers/sending-email/django/