Azure Functions における SendGrid のバインディング

この記事では、Azure Functions で SendGrid のバインディングを使用して電子メールを送信する方法について説明します。 Azure Functions では、SendGrid 用の出力バインディングがサポートされています。

これは、Azure Functions の開発者向けリファレンス情報です。 Azure Functions を初めて使用する場合は、先に次のリソースを参照してください。

拡張機能のインストール

インストールする拡張機能 NuGet パッケージは、関数アプリで使用している C# モードによって異なります。

関数は Functions ホストと同じプロセスで実行されます。 詳細については、「Azure Functions を使用する C# クラス ライブラリ関数を開発する」を参照してください。

拡張機能の機能性は、拡張機能のバージョンによって異なります。

プロジェクトにこの拡張機能を追加するには、NuGet パッケージ バージョン 3.x をインストールします。

バンドルのインストール

Functions バージョン 2.x から、HTTP 拡張機能は、host.json プロジェクト ファイルで指定されている拡張バンドルの一部です。 詳細については、「拡張機能のバンドル」を参照してください。

このバージョンの拡張機能は、拡張機能バンドル バージョン 2.x を使用して関数アプリで既に使用できる必要があります。

A C# 関数は、次の C# モードのいずれかを使用して作成できます。

  • インプロセス クラス ライブラリ: Functions ランタイムと同じプロセスで実行されるコンパイル済みの C# 関数。
  • 分離ワーカー プロセス クラス ライブラリ: ランタイムから分離されたワーカー プロセスで実行されるコンパイル済みの C# 関数。 分離ワーカー プロセスは、LTS および 非 LTS バージョンの .NET および .NET Framework で実行されている C# 関数をサポートするために必要です。
  • C# スクリプト: Azure portal で C# 関数を作成するときに主に使用されます。

次の例は、Service Bus キュー トリガーと SendGrid 出力バインディングを使用する C# 関数を示しています。

同期実行の例を次に示します。

using SendGrid.Helpers.Mail;
using System.Text.Json;

...

[FunctionName("SendEmail")]
public static void Run(
    [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] Message email,
    [SendGrid(ApiKey = "CustomSendGridKeyAppSettingName")] out SendGridMessage message)
{
    var emailObject = JsonSerializer.Deserialize<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; }
}

非同期実行の例を次に示します。

using SendGrid.Helpers.Mail;
using System.Text.Json;

...

[FunctionName("SendEmail")]
public static async Task Run(
 [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] Message email,
 [SendGrid(ApiKey = "CustomSendGridKeyAppSettingName")] IAsyncCollector<SendGridMessage> messageCollector)
{
    var emailObject = JsonSerializer.Deserialize<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 プロパティの設定を省略できます。

次の例は、function.json ファイルの Service 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;
};

現在、SendGrid バインドについての PowerShell の完全な例は利用できません。

次の例は、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")

次の例では、SendGrid 出力バインディングを使用してメールを送信するために、Java 関数ランタイム ライブラリ@SendGridOutput 注釈を使用しています。

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 構成ファイルを使用します。

インプロセス関数アプリでは、次のパラメーターをサポートする SendGridAttribute を使用します。

属性/注釈のプロパティ 説明
ApiKey API キーを含むアプリ設定の名前。 設定されていない場合、既定のアプリ設定名は AzureWebJobsSendGridApiKey です。
To (オプション) 受信者の電子メール アドレス。
From (オプション) 送信者の電子メール アドレス。
件名 (オプション) メールの件名。
Text (オプション) 電子メールの本文。

注釈

SendGridOutput 注釈を使用すると、次の構成値を指定することによって、SendGrid バインドを宣言的に構成できます。

構成

次の表は、function.json ファイルと SendGrid 属性/注釈で使用できるバインド構成のプロパティの一覧を示しています。

function.json のプロパティ 説明
type sendGrid に設定する必要があります。
direction out に設定する必要があります。
name 要求または要求本文の関数コードで使用される変数名。 戻り値が 1 つの場合、この値は $return です。
apiKey API キーを含むアプリ設定の名前。 設定されていない場合、既定のアプリの設定名は AzureWebJobsSendGridApiKey です。
to (オプション) 受信者の電子メール アドレス。
from (オプション) 送信者の電子メール アドレス。
subject (オプション) メールの件名。
text (オプション) 電子メールの本文。

省略可能なプロパティは、バインド内で既定値が定義されていて、プログラムで追加またはオーバーライドされる場合があります。

ローカルで開発する場合は、 コレクション内の local.settings.json ファイルにアプリケーション設定を追加します。

host.json 設定

このセクションでは、バージョン 2.x 以降でこのバインドに使用可能な構成設定について説明します。 host.json ファイルの設定は、関数アプリ インスタンスのすべての関数に適用されます。 次の host.json ファイルの例には、このバインドのバージョン 2.x 以降の設定のみが含まれています。 バージョン 2.x 以降のバージョンでの関数アプリ構成設定の詳細については、「Azure Functions の host.json のリファレンス」を参照してください。

Note

Functions 1.x の host.json のリファレンスについては、「host.json reference for Azure Functions 1.x (Azure Functions 1.x の host.json のリファレンス)」を参照してください。

{
    "version": "2.0",
    "extensions": {
        "sendGrid": {
            "from": "Azure Functions <samples@functions.com>"
        }
    }
}
プロパティ Default 説明
from 該当なし すべての関数の送信者の電子メール アドレス。

次のステップ