在Heroku上使用Django和Sendgrid发送SMTP电子邮件 [英] Sending SMTP email with Django and Sendgrid on Heroku

查看:107
本文介绍了在Heroku上使用Django和Sendgrid发送SMTP电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用SMTP和Django应用的sendgrid发送电子邮件.我可以在本地服务器上发送电子邮件,但是在我的Heroku应用程序上,我收到"SMTPServerDisconnected"错误消息,提示连接意外关闭.一旦部署到Heroku,是否可以通过sendgrid发送SMTP电子邮件?我似乎无法查找有关此内容的任何文档.

I'm trying to send email using SMTP and sendgrid for a Django app. I'm able to send emails on my local server, but on my heroku app I get an "SMTPServerDisconnected" error saying "connection unexpectedly closed. Is there a way to send SMTP email with sendgrid once deployed to Heroku? I can't seem to find any documentation on this.

这是我在settings.py中对电子邮件的设置:

Here are my settings for email in settings.py:

EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'EMAIL_HOST_USER'
EMAIL_HOST_PASSWORD = 'EMAIL_HOST_PASSWORD'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'email@email.com'

SENDGRID_API_KEY='SENDGRID_API_KEY'
SENDGRID_PASSWORD='SENDGRID_PASSWORD'
SENDGRID_USERNAME='SENDGRID_USERNAME'

请让我知道您用于发送SMTP电子邮件的设置.谢谢.

Please let me know what settings you use to send SMTP email. Thanks.

推荐答案

  1. 您需要进入Sendgrid dyno.导航到设置">"API密钥".

  1. You need to go into your Sendgrid dyno. Navigate to Settings>API Keys.

单击创建API密钥,在编写此密钥时,它是页面右上角的蓝色按钮.

Click on create API Key, at the time of writing this it is a blue button in the top right corner of the page.

复制它们为您生成的密钥,并将其粘贴到本地计算机上的某个位置,然后导航回到heroku页面.导航到您应用的设置",然后点击显示配置变量".现在,您应该看到所有环境变量的键值对.在密钥"列中添加"SENDGRID_API_KEY",并在值"列中添加从Sendgrid网站复制的密钥.此时,以下python代码应该可以正常工作:

copy the key that they generate for you and paste it somewhere on your local machine, also navigate back to your heroku page. Navigate to your app's Settings and click on "reveal config variables". You should now see key value pairs of all the environment variables. In the Key column add "SENDGRID_API_KEY" and in the value column add the key that you copied from the Sendgrid website. At this point the following python code should work:

sg = sendgrid.SendGridAPIClient(os.environ['SENDGRID_API_KEY'])
message = Mail(from_email='example@example.com', to_emails='example@example.com',
                           subject='Example Subject ', html_content='<strong>and easy to do anywhere, even with Python</strong>')
response = sg.send(message)

如果保留response变量,则可以将代码包装在try块中,try块可以尝试捕获错误.对不起格式,我仍然是堆栈溢出的新手.

If you keep the response variable you can wrap the code in a try except block can try to catch errors. Sorry for the formatting I am still new to posting on stack overflow.

这篇关于在Heroku上使用Django和Sendgrid发送SMTP电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆