通过 Sendgrid API 发送电子邮件时出错

Error when sending email through Sendgrid API

在我的生产服务器上,出现以下错误

"init() 得到了意外的关键字参数 'apikey'"

开发服务器上的相同代码正在运行。

我的生产服务器是 运行 gunicorn,我已经将环境变量 SENDGRID_API_KEY 添加到 gunicorn.service 文件中。我已经重新启动了 gunicorn 和 nginx。我可以看到环境变量已加载。

我调用发送邮件的方法如下:

def sendtestemail(to):
    sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
    from_email = Email("<myemail>@<mydomain>.com")
    to_email = Email(to)
    subject = "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())
    return [response.status_code, response.body, response.headers]

问题源于 sendgrid 6.0 中引入的重大更改。 apikey 的关键字参数已被删除并替换为位置参数。

要解决您的示例,请从您的参数中删除 apikey=,然后将 api_key 作为位置参数传递。

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

回顾之前的所有示例以及 GitHub 文档时,这可能有点令人困惑,但 this example on the official documentation 确实是正确的。


注意:我确实看到在提出您的问题时,您确实正确地遵循了我上面链接的文档。有一个 few issues opened 文档在相当长一段时间内仍然不准确,但在 5 月份得到解决。