你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Azure Functions SendGrid 绑定

This article explains how to send email by using SendGrid bindings in Azure Functions. Azure Functions 支持 SendGrid 的输出绑定。

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

Install extension

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

函数在独立的 C# 工作进程中执行。 若要了解详细信息,请参阅有关在独立工作进程中运行 C# Azure Functions 的指南

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

Add the extension to your project by installing the NuGet package, version 3.x.

Install bundle

Starting with Functions version 2.x, the HTTP extension is part of an extension bundle, which is specified in your host.json project file. To learn more, see extension bundle.

This version of the extension should already be available to your function app with extension bundle, version 2.x.

Example

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

  • 独立辅助角色模型:编译的 C# 函数,该函数在独立于运行时的工作进程中运行。 需要隔离的工作进程来支持长期支持 (LTS) 和非 LTS 版本的 .NET 和 .NET Framework 上运行的 C# 函数。
  • In-process model: Compiled C# function that runs in the same process as the Azure Functions runtime.
  • C# script: Used primarily when you create C# functions in the Azure portal.

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

The following example shows a SendGrid output binding in a function.json file and a JavaScript function that uses the binding.

Here's the binding data in the function.json file:

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

The configuration section explains these properties.

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 触发的函数。 可以在绑定配置中提供默认值。 For instance, the from email address is configured in 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();
    }
}

Attributes

Both in-process and isolated worker process C# libraries use attributes to define the output binding. C# 脚本改为使用 function.json 配置文件。

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

Attribute/annotation property Description
ApiKey 包含 API 密钥的应用设置的名称。 如果未设置,默认应用设置名称为 AzureWebJobsSendGridApiKey
To (可选)收件人的电子邮件地址。
From (可选)发件人的电子邮件地址。
Subject (可选)电子邮件的主题。
Text (可选)电子邮件内容。

Annotations

The SendGridOutput annotation allows you to declaratively configure the SendGrid binding by providing the following configuration values.

Configuration

The following table lists the binding configuration properties available in the function.json file and the SendGrid attribute/annotation.

function.json property Description
type 必须设置为 sendGrid
direction 必须设置为 out
name 在请求或请求正文的函数代码中使用的变量名称。 只有一个返回值时,此值为 $return
apiKey 包含 API 密钥的应用设置的名称。 If not set, the default app setting name is AzureWebJobsSendGridApiKey.
to (可选)收件人的电子邮件地址。
from (可选)发件人的电子邮件地址。
subject (可选)电子邮件的主题。
text (可选)电子邮件内容。

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

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

host.json settings

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

Note

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

{
    "version": "2.0",
    "extensions": {
        "sendGrid": {
            "from": "Azure Functions <samples@functions.com>"
        }
    }
}
Property Default Description
from n/a 所有函数的发件人电子邮件地址。

Next steps