Azure Functions v2 C# Script Async sample with SendGrid


I wanted to use Send Grid with Async method. However, all of the example on the Internet aim for Sync method. I'd like to introduce how to write it.

Note, this example is for Azure Functions V2.

Prerequisite

You need FunctionApp with V2 and SendGrid extension. After creating a FunctionApp then go to portal. Then you can change the Runtime version. For the SendGrid extension, click the "Integrate", then choose SendGrid as out put bindings. Then it ask you if you install the SendGrid extension. Just install it.

Code

Azure Functions V2 for the C# Script we can see a lot of changes. It has several change from V1.  SendGrid provide Mail class now it is SendGridMessage class. Also, the HttpRequestMessage truns into Microsoft.AspNetCore.Mvc.HttpRequest. Return value is from HttpResponseMessage into IActionResults .

I can't find any example for Async functions for C# Script for V2, however, I just make it Async and returns Task<IActionResults>.

 

Why it changed? The Azure Functions V2 uses ASP.NET Core MVC. You can refer this.

 

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/actions

run.csx

 

#r "Newtonsoft.Json"

#r "SendGrid"

using System.Net;

using Microsoft.AspNetCore.Mvc;

using Microsoft.Extensions.Primitives;

using Newtonsoft.Json; 

using SendGrid.Helpers.Mail; 

using System.Text;

public async static Task<IActionResult> Run(HttpRequest req, IAsyncCollector<SendGridMessage> messages, TraceWriter log)

{

 log.Info("SendGrid message"); 

 using (StreamReader reader = new StreamReader(req.Body, Encoding.UTF8))

 {

 var body = await reader.ReadToEndAsync();

 var message = new SendGridMessage();

 message.AddTo("tsushi@microsoft.com");

 message.AddContent("text/html", body);

 message.SetFrom("iot@alert.com");

 message.SetSubject("[Alert] IoT Hub Notrtification");

 await messages.AddAsync(message); 

 return (ActionResult)new OkObjectResult("The E-mail has been sent.");

 }

}

function.json

{

 "bindings": [

 {

 "authLevel": "function",

 "name": "req",

 "type": "httpTrigger",

 "direction": "in"

 },

 {

 "name": "$return",

 "type": "http",

 "direction": "out"

 },

 {

 "type": "sendGrid",

 "name": "messages",

 "apiKey": "SendGridAttribute.ApiKey",

 "direction": "out"

 }

 ],

 "disabled": false

}
You can also specify the e-mail settings on the function.json like this.
{
 "bindings": [
 {
 "authLevel": "function",
 "name": "req",
 "type": "httpTrigger",
 "direction": "in"
 },
 {
 "name": "$return",
 "type": "http",
 "direction": "out"
 },
 {
 "type": "sendGrid",
 "name": "messages",
 "apiKey": "SendGridAttribute.ApiKey",
 "to": "some@e-mail.com",
 "from": "iot@alert.com",
 "subject": "IoT Humidity Alert",
 "direction": "out"
 }
 ],
 "disabled": false
}

Resource


Comments (0)

Skip to main content