Skip to content

Instantly share code, notes, and snippets.

@mikamboo
Last active August 16, 2020 22:25
Show Gist options
  • Save mikamboo/9dc8e4f3af622e1a0e708cc32a21ac20 to your computer and use it in GitHub Desktop.
Save mikamboo/9dc8e4f3af622e1a0e708cc32a21ac20 to your computer and use it in GitHub Desktop.
Azure : SendGrid + Http trigger

Azure SendGrid HTTP trigger

Send emails with Azure functions + SendGrid biding.

Prerequistes

  • Azure account + subscription

Steps

  1. Connect to Azure portal.
  2. Go to create SendGrid Account from Azure portal (Add resource search SendGrid)
  3. Fill SendGrid Account creation form (select SendGrid free, and contacts informations ...), then deploy.
  4. Get API Key : Clic to Manage account link to be redirected to SendrGrid web console, then create new api key.
  5. Create new Azure functions application named SendGridAppFunc (Publish => Code, Stack => .Net Core, OS => Linux)
  6. Go to SendGridAppFunc settings, add new application parameter SendGridKey with praviously created API key as value
  7. Add new Azure HttpTrigger fonction named SendGridHttpFunc to SendGridAppFunc
  8. Update/replace function code with this snippet attached files run.csx and function.json

Test

  1. Get the function URL from Azure portal
curl -X POST -H "Content-Type: application/json" \
     -d '{ "OrderId": "78901", "CustomerName": "Mike P.O", "CustomerEmail": "[email protected]" }' \
     https://sendgridappfunc.azurewebsites.net/api/[YourFunctionName]?code=xxxxxxxxxxxxxxxxxxxxxx

Docs

{
"bindings": [
{
"authLevel": "function",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"post"
]
},
{
"type": "sendGrid",
"name": "$return",
"direction": "out",
"apiKey": "SendGridKey",
"from": "Azure Functions <[email protected]>"
}
],
"disabled": false
}
#r "SendGrid"
#r "Newtonsoft.Json"
using System;
using System.Net;
using Newtonsoft.Json;
using SendGrid.Helpers.Mail;
using Microsoft.Azure.WebJobs.Host;
public static async Task<SendGridMessage> Run(HttpRequest req, ILogger log)
{
log.LogInformation($"C# Queue trigger function processed order");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
Order order = new Order()
{
OrderId = data.OrderId,
CustomerName = data.CustomerName,
CustomerEmail = data.CustomerEmail
};
SendGridMessage message = new SendGridMessage()
{
Subject = $"Thanks for your order (#{order.OrderId})!"
};
message.AddTo(order.CustomerEmail, order.CustomerName);
message.AddContent("text/plain", $"{order.CustomerName}, your order ({order.OrderId}) is being processed!");
return message;
}
public class Order
{
public string OrderId { get; set; }
public string CustomerName { get; set; }
public string CustomerEmail { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment