Azure Functions SendGrid 绑定

本文介绍如何使用 Azure Functions 中的 SendGrid 绑定发送电子邮件。 Azure Functions 支持 SendGrid 的输出绑定。

此参考信息面向 Azure Functions 开发人员。 Azure Functions 的新手请从以下资源入手:

安装扩展

安装的扩展 NuGet 包取决于在函数应用中使用的 C# 模式:

函数在隔离的 C# 工作进程中执行。 若要了解详细信息,请参阅 指南,了解如何在隔离的工作进程中运行 C# Azure Functions。

扩展的功能因扩展版本而异:

通过安装 NuGet 包版本 3.x 将扩展添加到项目。

安装捆绑包

若要能够在应用中使用此绑定扩展,请确保项目的根目录中 host.json 文件包含以下 extensionBundle 引用:

{
    "version": "2.0",
    "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[4.0.0, 5.0.0)"
    }
}

在此示例中,version[4.0.0, 5.0.0)值指示 Functions 主机使用至少4.0.0小于但小于5.0.0的捆绑包版本,其中包括所有可能的 4.x 版本。 此表示法有效地在 v4.x 扩展捆绑包的最新可用次要版本上维护应用。

如果可能,应使用最新的扩展捆绑包主版本,并允许运行时自动维护最新的次要版本。 可以在 扩展捆绑包发布页上查看最新捆绑包的内容。 有关详细信息,请参阅 Azure Functions 扩展捆绑包。

示例:

可以使用以下 C# 模式之一创建 C# 函数:

  • 独立辅助角色模型:编译的 C# 函数,该函数在独立于运行时的工作进程中运行。 需要隔离的工作进程来支持长期支持 (LTS) 和非 LTS 版本的 .NET 和 .NET Framework 上运行的 C# 函数。
  • 进程内模型:在 Azure Functions 运行时所在的同一进程中运行的已编译 C# 函数。
  • C# 脚本:主要在 Azure 门户中创建 C# 函数时使用。

我们目前没有在函数应用(在独立工作进程中运行)中使用 SendGrid 绑定的示例。

以下示例演示 function.json 文件中的一个 SendGrid 输出绑定以及使用该绑定的 JavaScript 函数。

下面是 function.json 文件中的绑定数据:

{
    "bindings": [
        {
            "name": "$return",
            "type": "sendGrid",
            "direction": "out",
            "apiKey" : "MySendGridKey",
            "to": "{ToEmail}",
            "from": "{FromEmail}",
            "subject": "SendGrid output bindings"
        }
    ]
}

配置部分解释了这些属性。

JavaScript 代码如下所示:

module.exports = function (context, input) {
    var message = {
        "personalizations": [ { "to": [ { "email": "sample@sample.com" } ] } ],
        from: { email: "sender@contoso.com" },
        subject: "Azure news",
        content: [{
            type: 'text/plain',
            value: input
        }]
    };

    return message;
};

完整的 PowerShell 示例当前不可用于 SendGrid 绑定。

下面的示例演示了一个使用 SendGrid 绑定发送电子邮件的 HTTP 触发的函数。 可以在绑定配置中提供默认值。 例如,“发件人”电子邮件地址在“function.json”中配置。

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "type": "httpTrigger",
      "authLevel": "function",
      "direction": "in",
      "name": "req",
      "methods": ["get", "post"]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "type": "sendGrid",
      "name": "sendGridMessage",
      "direction": "out",
      "apiKey": "SendGrid_API_Key",
      "from": "sender@contoso.com"
    }
  ]
}

以下函数说明了如何为可选属性提供自定义值。

import logging
import json
import azure.functions as func

def main(req: func.HttpRequest, sendGridMessage: func.Out[str]) -> func.HttpResponse:

    value = "Sent from Azure Functions"

    message = {
        "personalizations": [ {
          "to": [{
            "email": "user@contoso.com"
            }]}],
        "subject": "Azure Functions email with SendGrid",
        "content": [{
            "type": "text/plain",
            "value": value }]}

    sendGridMessage.set(json.dumps(message))

    return func.HttpResponse(f"Sent")

以下示例使用 @SendGridOutput中的 注释来发送使用 SendGrid 输出绑定的电子邮件。

package com.function;

import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;

public class HttpTriggerSendGrid {

    @FunctionName("HttpTriggerSendGrid")
    public HttpResponseMessage run(

        @HttpTrigger(
            name = "req",
            methods = { HttpMethod.GET, HttpMethod.POST },
            authLevel = AuthorizationLevel.FUNCTION)
                HttpRequestMessage<Optional<String>> request,

        @SendGridOutput(
            name = "message",
            dataType = "String",
            apiKey = "SendGrid_API_Key",
            to = "user@contoso.com",
            from = "sender@contoso.com",
            subject = "Azure Functions email with SendGrid",
            text = "Sent from Azure Functions")
                OutputBinding<String> message,

        final ExecutionContext context) {

        final String toAddress = "user@contoso.com";
        final String value = "Sent from Azure Functions";

        StringBuilder builder = new StringBuilder()
            .append("{")
            .append("\"personalizations\": [{ \"to\": [{ \"email\": \"%s\"}]}],")
            .append("\"content\": [{\"type\": \"text/plain\", \"value\": \"%s\"}]")
            .append("}");

        final String body = String.format(builder.toString(), toAddress, value);

        message.setValue(body);

        return request.createResponseBuilder(HttpStatus.OK).body("Sent").build();
    }
}

特性

进程内和独立工作进程 C# 库都使用属性来定义输出绑定。 C# 脚本改为使用 function.json 配置文件。

在独立工作进程函数应用中,SendGridOutputAttribute 支持以下参数:

特性/注释属性 DESCRIPTION
ApiKey 包含 API 密钥的应用设置的名称。 如果未设置,默认应用设置名称为 AzureWebJobsSendGridApiKey。
至 (可选)收件人的电子邮件地址。
来自 (可选)发件人的电子邮件地址。
主题 (可选)电子邮件的主题。
文字 (可选)电子邮件内容。

批注

使用 SendGridOutput 注释,可以通过提供以下配置值以声明方式配置 SendGrid 绑定。

配置

下表列出了在 function.json 文件和 特性/注释中可用的绑定配置属性。

“function.json”属性 DESCRIPTION
类型 必须设置为 sendGrid。
方向 必须设置为 out。
名字 在请求或请求正文的函数代码中使用的变量名称。 此值是 $return 只有一个返回值时。
apiKey 包含 API 密钥的应用设置的名称。 如果未设置,默认应用设置名称为“AzureWebJobsSendGridApiKey”。
自 (可选)收件人的电子邮件地址。
起始 (可选)发件人的电子邮件地址。
主题 (可选)电子邮件的主题。
文本 (可选)电子邮件内容。

在绑定中可能会定义可选属性的默认值,并以编程方式添加或重写这些值。

在本地开发时,需要将应用程序设置添加到 集合中的 Values中。

host.json 设置

本部分介绍版本 2.x 及更高版本中此绑定可用的配置设置。 host.json 文件中的设置将应用于函数应用实例中的所有函数。 有关函数应用配置设置的详细信息,请参阅 Azure Functions 的host.json 参考。

注释

有关 Functions 1.x 中 host.json 的参考,请参阅 Azure Functions 1.x 的 host.json 参考。

{
    "version": "2.0",
    "extensions": {
        "sendGrid": {
            "from": "Azure Functions <samples@functions.com>"
        }
    }
}
资产 违约 DESCRIPTION
起始 n/a 所有函数的发件人电子邮件地址。

后续步骤