次の方法で共有


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)値は、少なくとも4.0.05.0.0未満のバンドル バージョン (4.x のすべての潜在的なバージョンを含む) を使用するように Functions ホストに指示します。 この表記は、v4.x 拡張機能バンドルの利用可能な最新のマイナー バージョンでアプリを効果的に維持します。

可能であれば、最新の拡張機能バンドルメジャー バージョンを使用し、ランタイムが最新のマイナー バージョンを自動的に維持できるようにする必要があります。 最新のバンドルの内容は、 拡張機能バンドルのリリース ページで確認できます。 詳細については、 Azure Functions 拡張機能バンドルに関するページを参照してください。

Example

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

  • 分離されたワーカー モデル: ランタイムから分離されたワーカー プロセスで実行されるコンパイル済みの C# 関数。 .NET および .NET Framework の長期サポート (LTS) および LTS 以外のバージョンで実行されている C# 関数をサポートするには、分離ワーカー プロセスが必要です。
  • インプロセス モデル: Azure Functions ランタイムと同じプロセスで実行されるコンパイル済み C# 関数。
  • C# スクリプト: 主に Azure portal で 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;
};

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

次の例は、SendGrid バインドを使用して電子メールを送信する、HTTP によってトリガーされる関数を示しています。 バインド構成では既定値を指定できます。 たとえば、 from 電子メール アドレスは 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 出力バインディングを使用してメールを送信するために、@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();
    }
}

Attributes

インプロセス分離ワーカー プロセスの両方の C# ライブラリは、属性を使用して出力バインドを定義します。 C# スクリプトでは、代わりに function.json 構成ファイルを使います。

分離ワーカー プロセス関数アプリでは、SendGridOutputAttribute は次のパラメーターをサポートします。

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

Annotations

SendGridOutput 注釈を使用すると、次の構成値を指定して、SendGrid バインディングを宣言的に構成できます。

Configuration

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

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

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

ローカルで開発する場合は、 コレクションの Valuesにアプリケーション設定を追加します。

host.json 設定

このセクションでは、バージョン 2.x 以降でこのバインドに使用できる構成設定について説明します。 host.json ファイルの設定は、関数アプリ インスタンスのすべての関数に適用されます。 関数アプリの構成設定の詳細については、 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>"
        }
    }
}
Property Default Description
from n/a すべての関数の送信者の電子メール アドレス。

次のステップ