Sending SMTP email with Django and Sendgrid on Heroku

前端 未结 1 1709
夕颜
夕颜 2021-01-25 03:07

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 s

相关标签:
1条回答
  • 2021-01-25 03:26
    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.

    0 讨论(0)
提交回复
热议问题