次の方法で共有


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# 関数。 .NET および .NET Framework の長期サポート (LTS) および LTS 以外のバージョンで実行されている 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;
};

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

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

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

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 要求または要求本文の関数コードで使用される変数名。 戻り値が 1 つの場合、この値は $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 のリファレンスについては、「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 すべての関数の送信者の電子メール アドレス。

Next steps