通过python访问API时出现奇怪的错误403禁止

4 python http-status-code-403 sendgrid sendgrid-api-v3

我正在尝试访问一些电子邮件统计信息:我的代码:

import json
import os
from sendgrid.helpers.stats import *
from sendgrid import *

# NOTE: you will need move this file to the root directory of this project to execute properly.

# Assumes you set your environment variable:
# https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key
sg = SendGridAPIClient(os.environ.get('SG****'))


def pprint_json(json_raw):
    print(json.dumps(json.loads(json_raw), indent=2, sort_keys=True))



def build_global_stats():
    global_stats = Stats()
    global_stats.start_date = '2020-01-13'
    global_stats.end_date = '2020-01-14'
    global_stats.aggregated_by = 'day'
    return global_stats.get()



def get_global_stats():
    stats_params = build_global_stats()
    response = sg.client.stats.get(query_params=stats_params)
    print(response.status_code)
    print(response.headers)
    pprint_json(response.body)


get_global_stats()
Traceback (most recent call last):

  File "<ipython-input-10-cee8ef5434a2>", line 35, in <module>
    get_global_stats()

  File "<ipython-input-10-cee8ef5434a2>", line 29, in get_global_stats
    response = sg.client.stats.get(query_params=stats_params)

  File "C:\Users\blah\AppData\Local\Continuum\anaconda3\lib\site-packages\python_http_client\client.py", line 262, in http_request
    self._make_request(opener, request, timeout=timeout)

  File "C:\Users\blah\AppData\Local\Continuum\anaconda3\lib\site-packages\python_http_client\client.py", line 178, in _make_request
    raise exc

ForbiddenError: HTTP Error 403: FORBIDDEN
Run Code Online (Sandbox Code Playgroud)

可以注意到,我收到了这个禁止的错误。这是什么原因?我该如何解决这个问题?这不是我这边被阻止的网站,所以不知道为什么我会收到此错误

小智 9

对我来说,只有在 SendGrid 上添加新的发件人并在“ from ”参数上使用此发件人后,它才起作用。

请按照本教程操作:

https://sendgrid.com/docs/ui/sending-email/senders/

然后,转到注册的电子邮件并确认发件人身份。之后,您应该能够发送电子邮件。