Pages

Advertisement

Wednesday, November 8, 2023

Azure Functions: Sending Email via SendGrid

 In this blog post, I will show you how to create an Azure Functions app that can send emails via SendGrid. SendGrid is a cloud-based email service that provides reliable and scalable email delivery. Azure Functions is a serverless compute service that lets you run code without managing servers or infrastructure. By combining these two services, you can easily send emails from your Azure Functions app without worrying about the underlying email infrastructure.


To get started, you will need the following:

- An Azure account with an active subscription. If you don't have one, you can create one for free here.
- A SendGrid account with an API key. If you don't have one, you can sign up for free here and follow the instructions to create an API key.
- Visual Studio Code with the Azure Functions extension installed. You can download Visual Studio Code here and install the extension from here.
- The Azure Functions Core Tools. You can install them from here.

Once you have everything set up, follow these steps to create and deploy your Azure Functions app:

1. Open Visual Studio Code and create a new folder for your project. Name it whatever you like, such as `EmailSender`.
2. In Visual Studio Code, press `Ctrl+Shift+P` to open the command palette and select `Azure Functions: Create New Project...`. Choose the folder you created in the previous step as the location for your project.
3. Select `C#` as the language for your project and `.NET Core 3.1` as the runtime version.
4. Select `HTTP trigger` as the template for your first function and name it `SendEmail`. Choose `Anonymous` as the authorization level for your function.
5. A new file named `SendEmail.cs` will be created in your project folder with some boilerplate code for your function. Replace the code in this file with the following:

6. In Visual Studio Code, open the `local.settings.json` file in your project folder and add a new setting named `SENDGRID_API_KEY` with the value of your SendGrid API key. This file is used to store app settings for local development and testing. Make sure not to commit this file to source control as it contains sensitive information.
7. In Visual Studio Code, press `F5` to run your function app locally. You should see a message in the terminal window that says `Http Functions: SendEmail: [POST] http://localhost:7071/api/SendEmail`.
8. To test your function, you can use a tool like Postman or curl to send a POST request to the function URL with a JSON body that contains the email parameters. For example, you can use the following curl command:

//csharp
using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SendGrid;
using SendGrid.Helpers.Mail;

namespace EmailSender
{
    public static class SendEmail
    {
        [FunctionName("SendEmail")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            // Parse the request body
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);

            // Get the email parameters from the request body
            string fromEmail = data?.fromEmail;
            string fromName = data?.fromName;
            string toEmail = data?.toEmail;
            string toName = data?.toName;
            string subject = data?.subject;
            string body = data?.body;

            // Validate the email parameters
            if (string.IsNullOrEmpty(fromEmail) || string.IsNullOrEmpty(toEmail) || string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(body))
            {
                return new BadRequestObjectResult("Please provide valid email parameters in the request body.");
            }

            try
            {
                // Create a SendGrid client with your API key
                var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
                var client = new SendGridClient(apiKey);

                // Create a SendGrid message object with the email parameters
                var from = new EmailAddress(fromEmail, fromName);
                var to = new EmailAddress(toEmail, toName);
                var msg = MailHelper.CreateSingleEmail(from, to, subject, body, body);

                // Send the email using the SendGrid client
                var response = await client.SendEmailAsync(msg);

                // Check the response status code and return accordingly
                if (response.StatusCode == HttpStatusCode.Accepted)
                {
                    return new OkObjectResult("Email sent successfully.");
                }
                else
                {
                    return new BadRequestObjectResult($"Email failed to send. Status code: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                // Log and return any exception that occurs
                log.LogError(ex, "An error occurred while sending email.");
                return new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }
        }
    }
}


No comments:

Post a Comment