How do I use SendGrid in an Azure Function?

3.2k views Asked by At

I'm trying to understand how I should be using SendGrid in an Azure Function that I'm developing in the Azure Portal. I've been coming at it from as many angles as Google has suggested but it seems there are many outdated ways of doing it that I can't resolve with what is available to me in the Azure Portal. Below is my current basic iteration of sending an email, I pulled this directly from the SendGrid blog (https://sendgrid.com/blog/using-sendgrid-with-azure-functions-to-send-mobile-app-survey-data). I've seen references to using a project.json file to ensure the SendGrid package is installed, but I have no way to create such a file within my function, I can only manipulate the run.csx and function.json files. Below is my code and the errors I'm running into. What am I missing?

#r "Newtonsoft.Json"
#r "SendGrid"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using SendGrid.Helpers.Mail;

public static void Run(HttpRequest req, ILogger log, out Message message)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    message = new Mail {
        Subject = "Test Notification"
    };

    string requestBody = new StreamReader(req.Body).ReadToEnd();

    Content content = new Content {
        Type = "text/html",
        Value = requestBody
    };
    
    message.AddContent(content);
}

Errors:
[Error] run.csx(10,58): error CS0246: The type or namespace name 'Message' could not be found (are you missing a using directive or an assembly reference?)
[Error] run.csx(14,19): error CS0246: The type or namespace name 'Mail' could not be found (are you missing a using directive or an assembly reference?)
Screenshot of my Azure Function

1

There are 1 answers

1
Rimaz Mohommed On BEST ANSWER

Maybe try using SendGridMessage message = new SendGridMessage()???

I'd first suggest you try the following to make sure your SendGrid flow works correctly :

  1. Create a new function of type "Send Grid" Notification. You will be able to see the proper C# on how to use SendGrid that way. See this Image See this Image

You can then update your existing code to get it working. I was able to create a sample HTTP triggered function to send a SendGrid message. I have attached the function.json and run.csx for your reference.

function.json

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "apiKey": "sendgridkey",
      "to": "[email protected]",
      "from": "[email protected]",
      "direction": "out",
      "type": "sendGrid"
    }
  ]
}

Here the "sendgridkey" is an app configuration with the SendGrid API key as its value. I've added dummy values for the emails.

My run.csx is as follows:

#r "SendGrid"
#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using SendGrid.Helpers.Mail;

public static async Task<SendGridMessage> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    
    SendGridMessage message = new SendGridMessage()
    {
        Subject = $"Thanks for your order (#{name})!"
    };

    message.AddContent("text/plain", "Your order is being processed now!!");
    return message;
}