Sendgrid-python: HTTP Error 401: Unauthorized

Created on 31 Oct 2016  Â·  19Comments  Â·  Source: sendgrid/sendgrid-python

Hello.
We experience a lot of 401 errors just after 28 October. Changing API key is not working. Could you say is that ok?
We are using sendgrid-python installed from pip like "pip install sendgrid".

Code:

            sg = sendgrid.SendGridAPIClient(api_key=API_KEY)
            subject = "Some subject"
            from_email = "[email protected]"
            to_email = "[email protected]"
            content = Content('text/html', html content)
            mail = Mail(Email(from_email), subject, Email(to_email), content)
            response = sg.client.mail.send.post(request_body=mail.get())
            msg, status = response.body, response.status_code
            logging.info(status)
            logging.info(msg)

Tried to set ENV variable but it doesn't help too.

Best regards,
Peter

question

All 19 comments

Actually that error simply means we exceeded monthly quota. Is that possible to change Exception 401 to more meaningful?

Thank @RaiaN! I'll pass along that feedback.

Hey @RaiaN what is the exact message you are receiving from the endpoint?

sh-3.2# python run_email.py
Traceback (most recent call last):
File "run_email.py", line 14, in
response = sg.client.mail.send.post(request_body=mail.get())
File "/Library/Python/2.7/site-packages/python_http_client/client.py", line 204, in http_request
return Response(self._make_request(opener, request))
File "/Library/Python/2.7/site-packages/python_http_client/client.py", line 138, in _make_request
return opener.open(request)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 437, in open
response = meth(req, response)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 550, in http_response
'http', request, response, code, msg, hdrs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 475, in error
return self._call_chain(args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(
args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 558, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized

using SendGrid's Python Library

https://github.com/sendgrid/sendgrid-python

import sendgrid
import os
from sendgrid.helpers.mail import *

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRIDKEY'))
from_email = Email("[email protected]")
to_email = Email("[email protected]")
subject = u"Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)

Hello @yuz835,

To rule out the API Key, could you please try this: https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/curl_examples.html#-Hello-World

If you still have issues, please reach out to https://support.sendgrid.com so they can dig into your account for further assistance.

Thanks!

the API key works with https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/curl_examples.html#-Hello-World
but still see urllib2.HTTPError: HTTP Error 401: Unauthorized
when using
import sendgrid
import os
from sendgrid.helpers.mail import *

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRIDKEY'))
from_email = Email("[email protected]")
to_email = Email("[email protected]")
subject = u"Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)

What is your dev platform? If if it's a Unix variant, can you go to your shell and type echo $SENDGRIDKEY to make sure it's set properly?

This one worked for me: https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/curl_examples.html#-Hello-World

but the python doesnt work, anyway, I made a workaround by using curl

Hello @yuz835,

Thanks for the follow up!

Were you able to try my suggestion above? I believe your issue with the Python library is that the SENDGRIDKEY environment variable is not being set correctly.

Hi, @thinkingserious ,

thanks, it works now, there is a typo in SENDGRIDKEY

Regards

I saw the same "Unauthorized" message when I generated the API key using my "teammate" account and apparently it did not have Mail "send" privileges. Worked after I used main admin account or upgrade the teammate permissions.

More about SendGrid "teammates" permissions : https://sendgrid.com/docs/User_Guide/Settings/teammates.html#-Configuring-permisisons

Thanks for the additional feedback @dushi27!

Hi, I also encounter this error but when I try this : https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/curl_examples.html#-Hello-World
it says 400 Bad Request. Help please.

HI @dalelantofindshare,

This means there is an issue with your API key. I recommend you reach out to our support team for assistance.

With Best Regards,

Elmer

Hi Elmer

So These are what I entered and I saw this in my sendgrid account :
SEND_GRID_API_KEY = 'SG.4j2-BrXyRnKcApYJ-9vcQw.C5asnXzm4q7Or0MecPXeoRipz_****0'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'dale*o'
EMAIL_HOST_PASSWORD = '
**
o'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'dale.
@**.com'
ACCOUNT_EMAIL_SUBJECT_PREFIX = 'Contact email reecived from ModernArbitration'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
Note : The asterisks are only for privacy purposes but they are really characters.
1)I've read here https://sendgrid.com/docs/Classroom/Send/How_Emails_Are_Sent/api_keys.html that "For sending via SMTP, provide the string apikey as the SMTP username, and use your API Key as the password."
2)While here https://sendgrid.com/docs/Classroom/Troubleshooting/Account_Administration/help_i_cant_find_my_smtp_username_and_password.html "Your SMTP username and password is the same username and password you provided when you signed up for SendGrid. We use the same set of credentials as the default means of logging into the Customer Portal and SMTP authentication."
What should i really follow? the 2nd one doesn't work. Please help. Thanks

Hello @dalelantofindshare,

Could you please provide me with your support ticket number? Thanks!

I am getting python_http_client.exceptions.UnauthorizedError: HTTP Error 401: Unauthorized while i was integrating sendgrid with python django.

I am getting following error :

urllib.error.HTTPError: HTTP Error 401: Unauthorized

Find : there was no api-key issue in mine case, SendGrid quota has exceeded the limit that why ,it giving this error in airflow dag.

Reslove : Exceed the sendgrid quota limit .

May be it will helpfull for you.

Was this page helpful?
0 / 5 - 0 ratings