Delen via


Azure Functions SendGrid-bindingen

This article explains how to send email by using SendGrid bindings in Azure Functions. Azure Functions ondersteunt een uitvoerbinding voor SendGrid.

Dit is referentie-informatie voor Azure Functions-ontwikkelaars. Als u nog geen ervaring hebt met Azure Functions, begint u met de volgende resources:

Install extension

Het NuGet-extensiepakket dat u installeert, is afhankelijk van de C#-modus die u gebruikt in uw functie-app:

Functies worden uitgevoerd in een geïsoleerd C#-werkproces. Zie De handleiding voor het uitvoeren van C# Azure Functions in een geïsoleerd werkproces voor meer informatie.

De functionaliteit van de extensie varieert afhankelijk van de extensieversie:

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

U kunt een C#-functie maken met behulp van een van de volgende C#-modi:

  • Geïsoleerd werkrolmodel: gecompileerde C#-functie die wordt uitgevoerd in een werkproces dat is geïsoleerd van de runtime. Er is een geïsoleerd werkproces vereist om C#-functies te ondersteunen die worden uitgevoerd op langetermijnondersteuning (LTS) en niet-LTS-versies voor .NET en .NET Framework.
  • 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.

We hebben momenteel geen voorbeeld voor het gebruik van de SendGrid-binding in een functie-app die wordt uitgevoerd in een geïsoleerd werkproces.

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.

Dit is de JavaScript-code:

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;
};

Volledige PowerShell-voorbeelden zijn momenteel niet beschikbaar voor SendGrid-bindingen.

In het volgende voorbeeld ziet u een door HTTP geactiveerde functie waarmee een e-mailbericht wordt verzonden met behulp van de SendGrid-binding. U kunt standaardwaarden opgeven in de bindingsconfiguratie. 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"
    }
  ]
}

De volgende functie laat zien hoe u aangepaste waarden voor optionele eigenschappen kunt opgeven.

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")

In het volgende voorbeeld wordt de @SendGridOutput aantekening uit de Runtime-bibliotheek van Java Functions gebruikt om een e-mailbericht te verzenden met behulp van de SendGrid-uitvoerbinding.

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#-script maakt in plaats daarvan gebruik van een function.json configuratiebestand.

In geïsoleerde werkprocesfunctie-apps ondersteunt de SendGridOutputAttribute volgende parameters:

Attribute/annotation property Description
ApiKey De naam van een app-instelling die uw API-sleutel bevat. Als dit niet is ingesteld, is AzureWebJobsSendGridApiKeyde standaardnaam van de app-instelling.
To (Optioneel) Het e-mailadres van de geadresseerde.
From (Optioneel) Het e-mailadres van de afzender.
Subject (Optioneel) Het onderwerp van het e-mailbericht.
Text (Optioneel) De e-mailinhoud.

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 Moet worden ingesteld op sendGrid.
direction Moet worden ingesteld op out.
name De naam van de variabele die wordt gebruikt in functiecode voor de aanvraag- of aanvraagbody. Deze waarde is $return wanneer er slechts één retourwaarde is.
apiKey De naam van een app-instelling die uw API-sleutel bevat. If not set, the default app setting name is AzureWebJobsSendGridApiKey.
to (Optioneel) Het e-mailadres van de geadresseerde.
from (Optioneel) Het e-mailadres van de afzender.
subject (Optioneel) Het onderwerp van het e-mailbericht.
text (Optioneel) De e-mailinhoud.

Optionele eigenschappen hebben mogelijk standaardwaarden gedefinieerd in de binding en kunnen programmatisch worden toegevoegd of overschreven.

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

host.json settings

In deze sectie worden de configuratie-instellingen beschreven die beschikbaar zijn voor deze binding in versie 2.x en hoger. Instellingen in het bestand host.json zijn van toepassing op alle functies in een exemplaar van een functie-app. Zie host.json naslaginformatie voor Azure Functions voor meer informatie over configuratie-instellingen voor functie-apps.

{
    "version": "2.0",
    "extensions": {
        "sendGrid": {
            "from": "Azure Functions <samples@functions.com>"
        }
    }
}
Property Default Description
from n/a Het e-mailadres van de afzender in alle functies.

Next steps