Sending SMTP email with Django and Sendgrid on Heroku

£可爱£侵袭症+ 提交于 2020-06-16 18:13:40

问题


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.

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'

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


回答1:


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

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

  3. 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)

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.



来源:https://stackoverflow.com/questions/53982067/sending-smtp-email-with-django-and-sendgrid-on-heroku

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!