【问题标题】:Sending mail using SendGrid in a Python script using Azure Function App使用 Azure Function App 在 Python 脚本中使用 SendGrid 发送邮件
【发布时间】:2019-12-20 12:27:47
【问题描述】:

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

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

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

以前有人做过这样的事吗?

【问题讨论】:

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


    【解决方案1】:

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

    Azure Functions Queue Trigger Python Sample that send email by using SendGrid bindings.
    SendGrid binding reference:
    https://docs.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 = "receiver@contoso.com"
    _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)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-06
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多