azure - 使用 Azure Function App 在 Python 脚本中使用 SendGrid 发送邮件

标签 azure azure-functions sendgrid azure-function-app

我有一个小的 Python 脚本,每天检查一些失败的进程。这每天都会通过时间触发器运行。

我希望脚本通过电子邮件向我发送所有失败进程的摘要。为此,我已经拥有一个 SendGrid 帐户,但我在 Azure 中创建了一个新帐户。

但是,我不确定如何在我的 Python 脚本中实现 SendGrid。 Azure 文档有一个 .NET 应用程序指南,但对我帮助不大。

以前有人做过类似的事情吗?

最佳答案

我在github上找到了这段代码,你可能需要稍微调整一下以支持最新的功能版本,

Azure Functions Queue Trigger Python Sample that send email by using SendGrid bindings.
SendGrid binding reference:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-sendgrid
"""
import os, json

_AZURE_FUNCTION_QUEUE_INPUT_ENV_NAME = "inputMessage"
_AZURE_FUNCTION_SENDGRID_OUTPUT_ENV_NAME = "outputMessage"
_SENDGRID_EMAIL_TO = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c2d5d3d5d9c6d5c2f0d3dfdec4dfc3df9ed3dfdd" rel="noreferrer noopener nofollow">[email protected]</a>"
_SENDGRID_EMAIL_SUBJECT = "Mail Subject"

# read the queue message
messageText = open(os.environ[_AZURE_FUNCTION_QUEUE_INPUT_ENV_NAME]).read()
print("Function script processed queue message '{0}'".format(messageText))

outmsg={
    "personalizations": [
        { 
            "to": [{ "email": _SENDGRID_EMAIL_TO }]
        }
    ],
    "subject": _SENDGRID_EMAIL_SUBJECT,
    "content": [
        {
            "type": 'text/plain',
            "value": messageText
        }
    ]
 }

# Send email using SendGrid (output name: outputMessage)
print('Sending email using SendGrid:', outmsg)
with open(os.environ[_AZURE_FUNCTION_SENDGRID_OUTPUT_ENV_NAME], 'wb') as f:
    json.dump(outmsg,f)

关于azure - 使用 Azure Function App 在 Python 脚本中使用 SendGrid 发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59425263/

相关文章:

用于调用 Office 365 和 Graph API REST 的 Azure AD 身份验证

Azure 流分析到 Cosmos 数据库

azure - 为什么功能应用程序突然停止工作?

node.js - Azure 函数 TypeScript 装饰器

azure - 用于生成 Azure 函数成功和失败计数线图的 Kusto 查询

python - 在使用 sendgrid 设置 django 期间出现错误 401

azure - 授予服务主体访问 ADLS 文件的正确方法

azure - 将消费计划上的 Azure Function App 设置为 64 位

azure - 如何在 Azure 市场中使用 Terraform 创建 Sengrid 订阅

php - 调用发送函数后如何获取 Laravel 邮件响应?