Azure Functions SendGrid 绑定Azure Functions SendGrid bindings

本文介绍如何使用 Azure Functions 中的 SendGrid 绑定发送电子邮件。This article explains how to send email by using SendGrid bindings in Azure Functions. Azure Functions 支持 SendGrid 的输出绑定。Azure Functions supports an output binding for SendGrid.

此参考信息面向 Azure Functions 开发人员。This is reference information for Azure Functions developers. Azure Functions 的新手请从以下资源入手:If you're new to Azure Functions, start with the following resources:

包 - Functions 1.xPackages - Functions 1.x

Microsoft.Azure.WebJobs.Extensions.SendGrid NuGet 包 2.x 版本中提供了 SendGrid 绑定。The SendGrid bindings are provided in the Microsoft.Azure.WebJobs.Extensions.SendGrid NuGet package, version 2.x. azure-webjobs-sdk-extensions GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk-extensions GitHub repository.

下表说明了如何在每个开发环境中添加对此绑定的支持。The following table tells how to add support for this binding in each development environment.

开发环境Development environment 添加支持To add support in
Functions 1.xFunctions 1.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#Local development - C# script, JavaScript, F# 自动Automatic
门户开发Portal development 自动Automatic

包 - Functions 2.xPackages - Functions 2.x

Microsoft.Azure.WebJobs.Extensions.SendGrid NuGet 包 3.x 版本中提供了 SendGrid 绑定。The SendGrid bindings are provided in the Microsoft.Azure.WebJobs.Extensions.SendGrid NuGet package, version 3.x. azure-webjobs-sdk-extensions GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk-extensions GitHub repository.

下表说明了如何在每个开发环境中添加对此绑定的支持。The following table tells how to add support for this binding in each development environment.

开发环境Development environment 添加支持To add support in
Functions 2.xFunctions 2.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#、Java 和 PythonLocal development - C# script, JavaScript, F#, Java and Python 注册扩展Register the extension
门户开发Portal development 添加输出绑定时安装Install when adding output binding

若要了解如何更新门户中的现有绑定扩展而不必重新发布函数应用项目,请参阅更新扩展To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

示例Example

参阅语言特定的示例:See the language-specific example:

C# 示例C# example

以下示例演示使用服务总线队列触发器和 SendGrid 输出绑定的 C# 函数The following example shows a C# function that uses a Service Bus queue trigger and a SendGrid output binding.

同步 C# 示例:Synchronous C# example:

[FunctionName("SendEmail")]
public static void Run(
    [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] Message email,
    [SendGrid(ApiKey = "CustomSendGridKeyAppSettingName")] out SendGridMessage message)
{
var emailObject = JsonConvert.DeserializeObject<OutgoingEmail>(Encoding.UTF8.GetString(email.Body));

message = new SendGridMessage();
message.AddTo(emailObject.To);
message.AddContent("text/html", emailObject.Body);
message.SetFrom(new EmailAddress(emailObject.From));
message.SetSubject(emailObject.Subject);
}

public class OutgoingEmail
{
    public string To { get; set; }
    public string From { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
}

异步 C# 示例:Asynchronous C# example:

[FunctionName("SendEmail")]
public static async void Run(
 [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] Message email,
 [SendGrid(ApiKey = "CustomSendGridKeyAppSettingName")] IAsyncCollector<SendGridMessage> messageCollector)
{
 var emailObject = JsonConvert.DeserializeObject<OutgoingEmail>(Encoding.UTF8.GetString(email.Body));

 var message = new SendGridMessage();
 message.AddTo(emailObject.To);
 message.AddContent("text/html", emailObject.Body);
 message.SetFrom(new EmailAddress(emailObject.From));
 message.SetSubject(emailObject.Subject);
 
 await messageCollector.AddAsync(message);
}

public class OutgoingEmail
{
 public string To { get; set; }
 public string From { get; set; }
 public string Subject { get; set; }
 public string Body { get; set; }
}

如果在应用设置中指定了名为“AzureWebJobsSendGridApiKey”的 API 密钥,则可以不设置特性的 ApiKey 属性。You can omit setting the attribute's ApiKey property if you have your API key in an app setting named "AzureWebJobsSendGridApiKey".

C# 脚本示例C# script example

以下示例演示 function.json 文件中的一个 SendGrid 输出绑定以及使用该绑定的 C# 脚本函数The following example shows a SendGrid output binding in a function.json file and a C# script function that uses the binding.

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "bindings": [
        {
          "type": "queueTrigger",
          "name": "mymsg",
          "queueName": "myqueue",
          "connection": "AzureWebJobsStorage",
          "direction": "in"
        },
        {
          "type": "sendGrid",
          "name": "$return",
          "direction": "out",
          "apiKey": "SendGridAPIKeyAsAppSetting",
          "from": "{FromEmail}",
          "to": "{ToEmail}"
        }
    ]
}

配置部分解释了这些属性。The configuration section explains these properties.

C# 脚本代码如下所示:Here's the C# script code:

#r "SendGrid"

using System;
using SendGrid.Helpers.Mail;
using Microsoft.Azure.WebJobs.Host;

public static SendGridMessage Run(Message mymsg, ILogger log)
{
    SendGridMessage message = new SendGridMessage()
    {
        Subject = $"{mymsg.Subject}"
    };
    
    message.AddContent("text/plain", $"{mymsg.Content}");

    return message;
}
public class Message
{
    public string ToEmail { get; set; }
    public string FromEmail { get; set; }
    public string Subject { get; set; }
    public string Content { get; set; }
}

Java 示例Java example

以下示例使用 Java 函数运行时库中的 @SendGridOutput 注释来发送使用 SendGrid 输出绑定的电子邮件。The following example uses the @SendGridOutput annotation from the Java functions runtime library to send an email using the SendGrid output binding.

@FunctionName("SendEmail")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
            @SendGridOutput(
                name = "email", dataType = "String", apiKey = "SendGridConnection", to = "test@example.com", from = "test@example.com",
                subject= "Sending with SendGrid", text = "Hello from Azure Functions"
                ) OutputBinding<String> email
            )
    {
        String name = request.getBody().orElse("World");

        final String emailBody = "{\"personalizations\":" +
                                    "[{\"to\":[{\"email\":\"test@example.com\"}]," +
                                    "\"subject\":\"Sending with SendGrid\"}]," +
                                    "\"from\":{\"email\":\"test@example.com\"}," +
                                    "\"content\":[{\"type\":\"text/plain\",\"value\": \"Hello" + name + "\"}]}";

        email.setValue(emailBody);
        return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
    }

JavaScript 示例JavaScript example

以下示例演示 function.json 文件中的一个 SendGrid 输出绑定以及使用该绑定的 JavaScript 函数The following example shows a SendGrid output binding in a function.json file and a JavaScript function that uses the binding.

下面是 function.json 文件中的绑定数据: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 代码如下所示:Here's the JavaScript code:

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
        }]
    };

    context.done(null, message);
};

属性Attributes

C# 类库中,使用 SendGrid 特性。In C# class libraries, use the SendGrid attribute.

有关可以配置的特性属性的信息,请参阅配置For information about attribute properties that you can configure, see Configuration. 下面是某个方法签名中的 SendGrid 特性示例:Here's a SendGrid attribute example in a method signature:

[FunctionName("SendEmail")]
public static void Run(
    [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] OutgoingEmail email,
    [SendGrid(ApiKey = "CustomSendGridKeyAppSettingName")] out SendGridMessage message)
{
    ...
}

有关完整示例,请参阅 C# 示例For a complete example, see C# example.

配置Configuration

下表解释了在 function.json 文件和 SendGrid 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the SendGrid attribute.

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 必需 - 必须设置为 sendGridRequired - must be set to sendGrid.
directiondirection 必需 - 必须设置为 outRequired - must be set to out.
namename 必需 - 在请求或请求正文的函数代码中使用的变量名称。Required - the variable name used in function code for the request or request body. 只有一个返回值时,此值为 $returnThis value is $return when there is only one return value.
apiKeyapiKey ApiKeyApiKey 包含 API 密钥的应用设置的名称。The name of an app setting that contains your API key. 如果未设置,默认应用设置名称为“AzureWebJobsSendGridApiKey”。If not set, the default app setting name is "AzureWebJobsSendGridApiKey".
toto ToTo 收件人的电子邮件地址。the recipient's email address.
fromfrom FromFrom 发件人的电子邮件地址。the sender's email address.
subjectsubject 主题Subject 电子邮件主题。the subject of the email.
texttext 文本Text 电子邮件内容。the email content.

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

host.json 设置host.json settings

本部分介绍版本 2.x 中可用于此绑定的全局配置设置。This section describes the global configuration settings available for this binding in version 2.x. 下面的示例 host.json 文件仅包含此绑定的 2.x 版本设置。The example host.json file below contains only the version 2.x settings for this binding. 有关版本 2.x 中的全局配置设置的详细信息,请参阅 Azure Functions 版本 2.x 的 host.json 参考For more information about global configuration settings in version 2.x, see host.json reference for Azure Functions version 2.x.

Note

有关 Functions 1.x 中 host.json 的参考,请参阅 Azure Functions 1.x 的 host.json 参考For a reference of host.json in Functions 1.x, see host.json reference for Azure Functions 1.x.

{
    "version": "2.0",
    "extensions": {
        "sendGrid": {
            "from": "Azure Functions <samples@functions.com>"
        }
    }
}
属性Property 默认Default 说明Description
fromfrom 不适用n/a 所有函数的发件人电子邮件地址。The sender's email address across all functions.

后续步骤Next steps