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

时间:2019-04-22 18:38:23

标签: 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]

1 个答案:

答案 0 :(得分:1)

问题源于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月便得到了解决。