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.

注意

2.x 版不會建立在ServiceBusTrigger實例中設定的主題或訂用帳戶。Version 2.x does not create the topic or subscription configured in the ServiceBusTrigger instance. 2.x 版是以Microsoft Azure為基礎,而且不會處理佇列管理。Version 2.x is based on Microsoft.Azure.ServiceBus and does not handle queue management.

下表說明如何在每個開發環境中為此繫結新增支援。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

下列範例說明的 C# 函式,可使用服務匯流排佇列觸發程序和 SendGrid 輸出繫結。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 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 SubjectSubject 電子郵件主旨。the subject of the email.
texttext TextText 電子郵件內容。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.

注意

有關 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/an/a 所有函式的寄件者電子郵件地址。The sender's email address across all functions.

後續步驟Next steps