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

Opt*_*ime 3 python django sendgrid sendgrid-api-v3

在我的生产服务器上,我收到以下错误

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]
Run Code Online (Sandbox Code Playgroud)

Cod*_*ent 5

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

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

    sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
Run Code Online (Sandbox Code Playgroud)

当回顾之前的所有示例以及 GitHub 文档时,这可能会有点令人困惑,但官方文档中的这个示例确实是正确的。


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