Forums

SendGrid Mail Not Working

Hi! I have a developer account, but I'm using my sister's free account to make her a website so that her username will be inside the url rather than mine (I'd rather not purchase a domain). I am trying to use SendGrid to send emails, though it is not working even when I use the example code on the SendGrid website, as I am getting this error: python_http_client.exceptions.UnauthorizedError: HTTP Error 401: Unauthorized

Here is the code I'm using to send the email which is mostly copied and pasted from the SendGrid website.

import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='from_email@example.com',
    to_emails='to@example.com',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')
try:
    sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sg.send(message)
except:
    render_template("index.html")

I read the help page, but it says that secret key is a Django setting, though if it also works for Flask, then I may be able to figure it out that way. Is this error a result of me using a free account, or is it a problem in the code or the way I set up the virtualenv? Thank you so much!

That looks like you're not authorizing with sendgrid correctly. Make sure that the environment variable is actually making it to that point in the code (prints to stderr will appear in your error log)

Ok, after following previous instructions on the website, I had created a file called sendgrid.env that contains the API Key and one called .gitignore that just contains "sendgrid.env" both in the same directory as my program. Do I need to add something in this line: "sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))" to make it go to sendgrid.env? Thank you for the response!

You don't need to change anything in that line, but you do need to load you env file in your web app. There are instructions on how to do that here