Azure Functions SendGrid 系結

本文說明如何在 Azure Functions 中使用 SendGrid 系結傳送電子郵件。 Azure Functions 支援 SendGrid 的輸出系結。

這是 Azure Functions 開發人員的參考資訊。 如果您不熟悉 Azure Functions,請從下列資源開始:

安裝擴充功能

您安裝的延伸模組 NuGet 套件取決於您在函式應用程式中使用的 C# 模式:

函式會在隔離的 C# 背景工作進程中執行。 若要深入瞭解,請參閱 在隔離背景工作程序中執行 C# Azure Functions 的指南。

擴充功能的功能會根據擴充功能版本而有所不同:

藉由安裝 NuGet 套件 3.x 版,將擴充功能新增至您的專案。

安裝套件組合

從 Functions 2.x 版開始,HTTP 擴充功能是延伸模組套件組合的一 部分,該套件會在您的host.json項目檔中指定。 若要深入瞭解,請參閱 延伸模組套件組合

此版本的延伸模組應該已可供您的函式應用程式使用,且具有 延伸模組套件組合 2.x 版。

範例

您可以使用下列其中一種 C# 模式來建立 C# 函式:

  • 隔離的背景工作模型:在與運行時間隔離的背景工作進程中執行的已編譯 C# 函式。 需要隔離的背景工作進程,才能支援在 LTS 和非 LTS 版本 .NET 和 .NET Framework 上執行的 C# 函式。
  • 同進程模型:在與 Functions 運行時間相同的進程中執行的已編譯 C# 函式。
  • C# 文稿:主要用於在 Azure 入口網站 中建立 C# 函式時。

重要

支援將於 2026 年 11 月 10 日結束進程模型。 強烈建議您將 應用程式移轉至隔離的背景工作模型 ,以取得完整支援。

我們目前沒有在隔離背景工作進程中執行的函式應用程式中使用 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;
};

完整的 PowerShell 範例目前不適用於 SendGrid 系結。

下列範例示範使用 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")

下列範例會@SendGridOutput使用 Java 函式運行時間連結庫中註釋,使用 SendGrid 輸出系結傳送電子郵件。

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組態檔。

隔離的背景工作進程 函式應用程式中,支援 SendGridOutputAttribute 下列參數:

Attribute/annotation 屬性 描述
ApiKey 包含 API 金鑰的應用程式設定名稱。 如果未設定,預設應用程式設定名稱為 AzureWebJobsSendGridApiKey
目標 (選擇性)收件者的電子郵件位址。
(選擇性)寄件者的電子郵件位址。
主體 (選擇性)電子郵件的主旨。
Text (選擇性)電子郵件內容。

註釋

SendGridOutput 註釋可讓您藉由提供下列組態值,以宣告方式設定 SendGrid 系結。

組態

下表列出function.json檔案和SendGrid屬性/註釋中可用的系結組態屬性。

function.json 屬性 描述
type 必須設定為 sendGrid
direction 必須設定為 out
name 用於要求或要求主體之函式程式代碼中的變數名稱。 當只有一個傳回值時,這個值 $return 就會是 。
apiKey 包含 API 金鑰的應用程式設定名稱。 如果未設定,默認應用程式設定名稱為 AzureWebJobsSendGridApiKey
to (選擇性)收件者的電子郵件位址。
from (選擇性)寄件者的電子郵件位址。
subject (選擇性)電子郵件的主旨。
text (選擇性)電子郵件內容。

選擇性屬性可能會在系結中定義預設值,並以程序設計方式新增或覆寫。

當您在本機開發時,請在集合中的 local.settings.json 檔案Values中新增應用程式設定。

host.json 設定

本節說明 2.x 版和更新版本中此系結可用的組態設定。 host.json檔案中的 設定 會套用至函式應用程式實例中的所有函式。 下列範例host.json檔案只包含此系結的 2.x+ 版設定。 如需 2.x 版和更新版本中函式應用程式組態設定的詳細資訊,請參閱 Azure Functions 的host.json參考。

注意

如需 Functions 1.x 中host.json的參考,請參閱 Azure Functions 1.x 的host.json參考。

{
    "version": "2.0",
    "extensions": {
        "sendGrid": {
            "from": "Azure Functions <samples@functions.com>"
        }
    }
}
屬性 預設 描述
from n/a 所有函式的寄件者電子郵件地址。

下一步