HTTPError: HTTP错误401:未经授权的sendgrid集成python问题

10
def sendEmail(to,apNumber,paperType,zipedFile):

    sg = sendgrid.SendGridAPIClient(apikey=os.environ.get("API-KEY"))

    to_email = mail.Email( "to@email.com")
    from_email = mail.Email( "from@email.com" )
    subject = 'This is a test email'
    content = mail.Content('text/plain', 'Example message.')
    message = mail.Mail(from_email, subject, to_email, content)
    response = sg.client.mail.send.post(request_body = message.get())
    return response

你确定已经设置了 API-KEY 环境变量吗?你使用的是什么操作系统(在 Windows 上,API-KEY 是一个有效的环境变量名称,但 *nix 不允许在名称中使用 -)。 - mata
我正在使用Ubuntu 16.0。请问如何为API设置环境变量? - vinay
通常在运行程序之前,您需要在 shell 中导出它,例如 export API_KEY="..." - 更多信息请参见 这里 - mata
6个回答

8

设置环境变量。

要设置环境变量,请按照以下三个步骤进行操作:

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

是的,设置了环境变量之后,我的问题得到了解决。谢谢。 - vinay

3

我在使用PHP时遇到了“HTTP/1.1 401 未经授权”的错误。请参见截图。

enter image description here

我通过从API密钥中删除getenv()解决了这个问题。

替换为:

$apiKey = getenv("SendGrid_API_Key");
$sendgrid = new \SendGrid($apiKey);

使用:

$apiKey = ("SendGrid_API_Key");
$sendgrid = new \SendGrid($apiKey);

3
    import os
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import Mail
    message = Mail(
            from_email='...@gmail.com',
            to_emails='....@gmail.com',
            subject='Sending with Twilio SendGrid is Fun',    
            html_content='<strong>and easy to do anywhere, even with Python</strong>')
    try:
    **sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))**

        response = sg.send(message)
        print(response.status_code)
        print(response.body)
        print(response.headers)
    except Exception as e:
        print(e)

我遇到了同样的错误 "UnauthorizedError: HTTP Error 401: Unauthorized"

我对代码进行了重构,从

sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))

改为

sg=SendGridAPIClient('......IeltIytmFYeQ0aSOt2UBYvv2E6Xh...')

然后它开始工作了。

我在SendGrid门户中更改了API密钥设置,使其具有完全访问权限。


1

我的问题是,尽管

sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))

当脚本从终端调用时,它可以正常工作,但是当它从浏览器中的JavaScript文件调用时却不能。这是因为在这种情况下os.environ.get实际上是不同的。 直接使用API_KEY是解决方案:

sg = SendGridAPIClient(api_key='SG.tbd')

但这不安全吗?API密钥不应该存储为环境变量吗? - undefined

0

我创建了一个新的密钥,解决了我的问题。具体问题仍然未知,因为之前它是可以正常运行的。


0
对我来说,这个错误是因为我使用了错误的密钥。实际上,当你创建 API 密钥时,需要使用第一次创建时生成的密钥,而此后不能再编辑。因此,你必须点击“创建 API 密钥”按钮并使用该密钥。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接