다음을 통해 공유


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# 모드에 따라 다릅니다.

Functions는 격리된 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;
};

전체 PowerShell 예제는 현재 SendGrid 바인딩에 사용할 수 없습니다.

다음 예제에서는 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")

다음 예제에서는 Java 함수 런타임 라이브러리@SendGridOutput주석을 사용하여 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();
    }
}

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 요청 또는 요청 본문에 대한 함수 코드에 사용되는 변수 이름입니다. 이 값은 $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의 참조는 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