【发布时间】:2022-10-20 20:45:15
【问题描述】:
我的代码运行每 1 小时发送一次电子邮件的脚本。 该脚本运行良好,直到 Sendgrid 导致错误 HTTP 401 Unauthorized。 我在网上查了一下,发现这可能是由于错误的 API 密钥或在 python 代码中没有正确导入 API。但到目前为止,我的代码运行良好。
sg = sendgrid.SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
def send_mail(to_email, subject, message, from_email=To("fromemail@id")):
"""
Input : to_email_list , subject , message string , from_email
Action: sends mail to all the recipients mentioned in the to_ids list
"""
try:
content = Content("text/html", message)
mail = Mail(from_email, to_email, subject, content)
mail_json = mail.get()
print("MAIL JSON", mail_json)
response = sg.client.mail.send.post(request_body=mail_json)
print(response.headers)
print("response code :", response.status_code)
print(
content,
)
return True
except Exception as e:
print(e)
return False
send_mail_utils.send_mail('toemail','testing','This is the message')
我尝试了以下方法:
- 在
sendgrid.SendGridAPIClient(API)中直接传递api token id - 使用新的 API 令牌
【问题讨论】:
-
您在哪里运行此代码 - 在托管服务或本地计算机上?我建议尝试从另一台设备运行它,或者直接从 REPL 运行它来测试 API 密钥。