【问题标题】:Sendgrid Introduction Throws Forbidden ErrorSendgrid 介绍抛出 Forbidden 错误
【发布时间】:2020-04-14 15:34:32
【问题描述】:

我正在运行 Sendgrid 的 intro material for Python,但执行示例代码会引发 403-Forbidden 错误。

我采取的步骤:

  1. 按照说明创建 API 密钥和sendgrid.env 文件。
  2. 使用 python 3.5 创建 conda 环境:conda create -n sendgrid python=3.5
  3. 安装sendgrid:(sendgrid) pip install sendgrid
  4. 运行示例:(sendgrid) python main.py

其中main.py 包含从上面链接的示例页面复制的确切代码。

问题:运行main.py会抛出错误HTTP Error 403: Forbidden

我尝试过的事情:

  • 我尝试在该示例中切换电子邮件,但没有改变结果。
  • 我也尝试了相同的流程,但使用的是 NodeJS,但结果相同。

关于我做错了什么有什么想法吗?

【问题讨论】:

    标签: python sendgrid


    【解决方案1】:

    授予 API Key 完全访问权限,按照以下步骤操作:

    1. 设置
    2. API 密钥
    3. 编辑 API 密钥
    4. 完全访问权限
    5. 更新

    将您的域列入白名单,按照以下步骤操作:

    1. 设置
    2. 发件人身份验证
    3. 域认证
    4. 选择 DNS 主机
    5. 输入您的域名
    6. 复制所有记录并将它们放入您的高级 DNS 管理控制台中

    注意:添加记录时,请确保主机中没有域名。裁剪出来。

    如果您不想验证域,您也可以尝试使用单一发件人验证

    注意:记录开始运行可能需要一些时间。


    如果你使用 pylinter,e.message 会说

    Instance of 'Exception' has no 'message' member
    

    这是因为message 属性是由sendgrid 动态生成的,因为它在运行时之前不存在,所以 pylinter 无法访问。

    因此,为防止这种情况,在文件顶部或print(e.message) 行上方,您需要添加以下任一内容,它们的含义相同-

    # pylint: disable=no-member
    

    E1101 是no-member 的代码,更多here

    # pylint: disable=E1101
    

    现在下面的代码应该适合您了。只要确保您在环境中设置了SENDGRID_API_KEY。如果没有,您也可以直接将其替换为os.environ.get("SENDGRID_API_KEY"),但这不是一个好习惯。

    # pylint: disable=E1101
    
    import os
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import Mail
    
    message = Mail(
        from_email="from_email@your-whitelisted-domain.com",
        to_emails=("recipient1@example.com", "recipient2@example.com"),
        subject="Sending with Twilio SendGrid is Fun",
        html_content="<strong>and easy to do anywhere, even with Python</strong>")
    try:
        sg = SendGridAPIClient(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.message)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      • 2013-05-06
      相关资源
      最近更新 更多