Skip to main content
 首页 » 编程设计

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

2024年11月24日3java哥

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

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 月份得到了解决。