Bootstrap FreeKB - SendGrid - Resolve "401 Unauthorized"
SendGrid - Resolve "401 Unauthorized"

Updated:   |  SendGrid articles

Let's say you get 401 Unauthorized when attempting to send an email using SendGrid, perhaps like this using SendGrid and Python.

#!/usr/bin/python3
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='from@example.com',
    to_emails='to@example.com',
    subject='Hello',
    html_content='<strong>World</strong>')

try:
  sg = SendGridAPIClient('SG.abcdefg123456789abcdefg123456789abcdefg123456789abcdefg123456789ab')
except Exception as exception:
  print(f"got the following exception when attempting to create the sg object: {exception}")
else:
  print(f"successfully created the sg object")

try:
  sg.send(message)
except Exception as exception:
  print(f"got the following exception when attempting to create the sg.send(message): {exception}")
else:
  print(f"successfully sent email")

 

This may be some issue with the API key being used, SG.abcdefg123456789abcdefg123456789abcdefg123456789abcdefg123456789abcde in this example.

When testing/debugging, you can probably set the API key to Full Access. At https://sendgrid.com/ select Settings > API Keys > edit API Key and ensure Full Access is selected.

 

I once had this issue and no matter what I did in Python, I just kep on getting 401 Unauthorized. But when I tried send an email using cURL, I got "Maximum credits exceeded" instead of 401 Unauthorized. 

~]$ curl \
--request POST \
--url https://api.sendgrid.com/v3/mail/send --header "Authorization: Bearer SG.abcdefg123456789abcdefg123456789abcdefg123456789abcdefg123456789ab" \
--header 'Content-Type: application/json' \
--data '{"personalizations": [{"to": [{"email": "test@example.com"}]}],"from": {"email": "test@example.com"},"subject": "Sending with SendGrid is Fun","content": [{"type": "text/plain", "value": "and easy to do anywhere, even with cURL"}]}'

{"errors":[{"message":"Maximum credits exceeded","field":null,"help":null}]}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f0df7a in the box below so that we can be sure you are a human.