sendgrid/sendgrid-python

HTTP Error 401: Unauthorized occures on Linux but runs fine on Windows

Sshahar opened this issue · 4 comments

Issue Summary

On ubuntu-server 20.04, the exact same code that would work on a Win10 machine doesn't work.

I've tried checking the headers, and they are identical (including the Bearer token value). same request.host value, different OS and python version (on win10 Python 3.9.5)

Code Snippet

mail_sender = SendMail()
mail_sender(file_path="report.xlsx")

import base64

from sendgrid.helpers.mail import (
    Mail, Attachment, FileContent, FileName,
    FileType, Disposition, ContentId)
from sendgrid import SendGridAPIClient


class SendMail:
    @staticmethod
    def _send(*args, **kwargs):
        message = Mail(
            from_email='me@example.com',
            to_emails=['me@example.com'],
            subject='Daily report',
            html_content='<strong>Sent from a python script written by me</strong>')

        file_path = kwargs['file_path']
        with open(file_path, 'rb') as f:
            data = f.read()

        encoded = base64.b64encode(data).decode()
        attachment = Attachment()
        attachment.file_content = FileContent(encoded)
        attachment.file_type = FileType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        attachment.file_name = FileName('report.xlsx')
        attachment.disposition = Disposition('attachment')
        attachment.content_id = ContentId('Example Content ID')
        message.attachment = attachment
        try:
            sendgrid_client = SendGridAPIClient('API_KEY')
            response = sendgrid_client.send(message)
            print(response.status_code)
            print(response.body)
            print(response.headers)
        except Exception as e:
            print(e)

    def __call__(self, *args, **kwargs):
        self._send(*args, **kwargs)

Exception/Log

This line raises an exception:

response = sendgrid_client.send(message)
HTTP Error 401: Unauthorized

Technical details:

  • sendgrid-python version: 6.7.1
  • python version: 3.6.9

I got the same, I got the exact same code as in the doc, got my API Key in my .env, but facing this error when I run my test.php ->

401
Array
(
[0] => HTTP/1.1 401 Unauthorized
[1] => Server: nginx
[2] => Date: Wed, 28 Jul 2021 14:38:08 GMT
[3] => Content-Type: application/json
[4] => Content-Length: 88
[5] => Connection: keep-alive
[6] => Access-Control-Allow-Origin: https://sendgrid.api-docs.io
[7] => Access-Control-Allow-Methods: POST
[8] => Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
[9] => Access-Control-Max-Age: 600
[10] => X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html
[11] => Strict-Transport-Security: max-age=600; includeSubDomains
[12] =>
[13] =>
)
{"errors":[{"message":"Permission denied, wrong credentials","field":null,"help":null}]}

And here is my test.php :

use SendGrid\Mail\Mail;

require 'vendor/autoload.php';

$email = new Mail();
$email->setFrom("test@example.com", "Example User");
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addTo("test@example.com", "Example User");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent(
"text/html", "and easy to do anywhere, even with PHP"
);

$file_encoded = base64_encode(file_get_contents('my_file.txt'));
$email->addAttachment(
$file_encoded,
"application/text",
"my_file.txt",
"attachment"
);

$sendgrid = new SendGrid(getenv('SENDGRID_API_KEY'));
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage(). "\n";
}

Hi @Sshahar can you try logging the error response body to get more details about why it's failing: print(e.body)

Closing due to inactivity. Please reopen if further help is needed.