Azure

How To Ship E mail Utilizing SendGrid With Azure Perform In .NET Core

Introduction

 

This text demonstrates the right way to ship e-mail from Azure Perform utilizing SendGrid. We’ll construct capabilities that can push and pull e-mail content material from queue storage and ship emails to recipient. To implement this end-to-end workflow, we’re going to create two Azure capabilities:

  1. The primary operate is predicated on an HTTP set off that can create a queue storage and push some dummy e-mail content material into it.
  2. The second operate is predicated on a queue set off that can course of every queue merchandise and skim respective e-mail content material from it and ship e-mail to the recipient utilizing SendGridMessage consumer.

Conditions

  • Fundamental information of Azure Perform.
  • Azure storage account already created.
  • .NET Core SDK 3.1 put in in your PC.
  • Azure storage emulator put in. That is out there as a part of the Microsoft Azure SDK. Test right here for extra particulars.

    HTTP set off operate to push messages into the queue (first operate)

     

    The aim of this operate is to push some dummy e-mail content material right into a queue in order that when the queue set off will occur later by one other operate, that operate will learn the content material from the queue. 

     

    NOTE

    This operate is elective. If you’ll be able to create your personal dummy JSON information right into a queue referred to as “email-queue“, then you’ll be able to skip this operate to create it. However I might suggest creating this operate which can enable you to grasp the tip to finish circulation.

     

    Beneath sequential steps shall be carried out by this operate :

    1. Create a queue referred to as “email-queue” if it would not exist within the storage account.
    2. Create a JSON object with a singular Id and HTML e-mail content material by loop. That is for only a demo e-mail content material. Primarily based in your want, you’ll be able to create static or dynamic HTML e-mail content material.
    3. Add that JSON object as a queue message into “email-queue”. 

    Let’s create an empty Azure Perform app venture from Visual Studio.

     

     

    As soon as a newly created answer is loaded, right-click on operate venture => Click on on Add => Click on on New Azure Perform… => Give a operate identify as “UploadEmailMessagesHttpTriggerFunction.cs” => Click on on Add => Choose “Http Set off” => Click on on Create.

     

    How to Send Email Using SendGrid with Azure Function in .NET Core

     

    Now set up the required NuGet packages within the venture.

    • Microsoft.Azure.WebJobs
    • Microsoft.Azure.WebJobs.Extensions.Storage

    Now we’re prepared to change the default template of the operate. Modify the Run technique so as to add ExecutionContext which shall be used to entry storage connection string from JSON file or from operate configuration settings on Azure.

     

    UploadEmailMessagesHttpTriggerFunction.cs

    1. utilizing System;  
    2. utilizing System.IO;  
    3. utilizing System.Threading.Duties;  
    4. utilizing Microsoft.AspNetCore.Mvc;  
    5. utilizing Microsoft.Azure.WebJobs;  
    6. utilizing Microsoft.Azure.WebJobs.Extensions.Http;  
    7. utilizing Microsoft.AspNetCore.Http;  
    8. utilizing Microsoft.Extensions.Logging;  
    9. utilizing Newtonsoft.Json;  
    10. utilizing Microsoft.Azure.Storage.Queue;  
    11. utilizing Microsoft.Azure.Storage.Blob;  
    12. utilizing Microsoft.Azure.Storage;  
    13. utilizing Microsoft.Extensions.Configuration;  
    14.   
    15. namespace AzFunctions  
    16. {  
    17.     public static class UploadEmailMessagesHttpTriggerFunction  
    18.     {  
    19.         [FunctionName(“UploadEmailMessagesHttpTriggerFunction”)]  
    20.         public static async Activity<IActionResult> Run(  
    21.             [HttpTrigger(AuthorizationLevel.Function, “get”“post”, Route = null)] HttpRequest req,  
    22.             ILogger log,  
    23.             ExecutionContext context)  
    24.         {  
    25.             log.LogInformation($“C# Http set off operate executed at: {DateTime.Now}”);  
    26.             CreateQueueIfNotExists(log, context);  

    27.             for (int i = 1; i <= 5; i++)  
    28.             {  
    29.                 string randomStr = Guid.NewGuid().ToString();  
    30.                 var serializeJsonObject = JsonConvert.SerializeObject(
    31.                                              new { 
    32.                                                    ID = randomStr, 
    33.                                                    Content material = $“<html><physique><h2> This is a Pattern HTML content material {i}! </h2></physique></html>”
    34.                                                  });  
    35.   
    36.                 CloudStorageAccount storageAccount = GetCloudStorageAccount(context);
    37.                 CloudQueueClient cloudQueueClient = storageAccount.CreateCloudQueueClient();  
    38.                 CloudQueue cloudQueue = cloudQueueClient.GetQueueReference(“email-queue”);  
    39.                 var cloudQueueMessage = new CloudQueueMessage(serializeJsonObjectfalse); 
    40.  
    41.                 await cloudQueue.AddMessageAsync(cloudQueueMessage);  
    42.             }  
    43.   
    44.             return new OkObjectResult(“UploadEmailMessagesHttpTriggerFunction executed efficiently!!”);  
    45.         }  
    46.  
    47.         non-public static void CreateQueueIfNotExists(ILogger logger, ExecutionContext executionContext)  
    48.         {  
    49.             CloudStorageAccount storageAccount = GetCloudStorageAccount(executionContext);  
    50.             CloudQueueClient cloudQueueClient = storageAccount.CreateCloudQueueClient();  
    51.             string[] queues = new string[] { “email-queue” };  
    52.             foreach (var merchandise in queues)  
    53.             {  
    54.                 CloudQueue cloudQueue = cloudQueueClient.GetQueueReference(merchandise);  
    55.                 cloudQueue.CreateIfNotExistsAsync(); 
    56.             }  
    57.         }  
    58.         non-public static CloudStorageAccount GetCloudStorageAccount(ExecutionContext executionContext)  
    59.         {  
    60.             var config = new ConfigurationBuilder().SetBasePath(executionContext.FunctionAppDirectory)  
    61.                                                    .AddJsonFile(“native.settings.json”truetrue)
    62.                                                    .AddEnvironmentVariables()
    63.                                                    .Construct();  
    64.             CloudStorageAccount storageAccount = CloudStorageAccount.Parse(config[“CloudStorageAccount”]);  
    65.             return storageAccount;  
    66.         }  
    67.     }   
    68. }  

    Open native.settings.json and add CloudStorageAccount connection string which is required for testing from native.

     

    This worth yow will discover out of your Azure storage account. For that, log in to Azure account => Go to storage account => Click on on Entry Keys below settings on left menu => You will note two keys there => Copy anybody of the connection sting => Paste that into native.settings.json file in your venture.

    1. “Values”: {  
    2.     “AzureWebJobsStorage”“UseDevelopmentStorage=true”,  
    3.     “FUNCTIONS_WORKER_RUNTIME”“dotnet”,  
    4.     “CloudStorageAccount”“DefaultEndpointsProtocol=https;AccountName=yourStorageAccountName;AccountKey=;EndpointSuffix=core.home windows.internet,  
    5.     “SendgridAPIKey”“”  
    6.   }  

    Let’s run the operate and replica the HTTP URL from the operate console window and paste it into the browser.

     

    How to Send Email Using SendGrid with Azure Function in .NET Core

     

    As soon as it’s executed you will note the message “UploadEmailMessagesHttpTriggerFunction executed efficiently!!”.

     

    Let’s confirm the storage account, you will note queue created with a message ID and a few pattern messages are pushed into Queue.

     

    Wonderful!

     

    Now publish the operate app on right-clicking on the answer and click on on Publish. In case you want any reference on the right way to publish the operate app, please take a look at the part “Deploy Azure Perform from Visual Studio” in this text.

     

    As soon as publish is profitable from VS, you will note the newly created azure operate on the Azure portal.

     

    How to Send Email Using SendGrid with Azure Function in .NET Core

     

    Now modify operate configuration so as to add extra settings as “CloudStorageAccount” and replica the worth from the storage account. Click on on save.

     

    How to Send Email Using SendGrid with Azure Function in .NET Core

     

    Let’s navigate to the operate and click on on “Click on+Check” => Click on on Check/Run to run it. As soon as it’s successful, you’ll be able to cross-verify uploaded content material on the container and queue from the storage account.

     

    How to Send Email Using SendGrid with Azure Function in .NET Core 

     

    Superior! We’re performed with our first operate.

    Join a SendGrid account

     

    To ship e-mail utilizing SendGrid, we should always have SendGrid API Keys. Create a free SendGrid account and create API Key from settings. That is required as a part of your second operate to function.

     

    Within the Azure portal menu or the house web page, choose Create a useful resource.

    1. Seek for and choose SendGrid Accounts.
    2. Full the signup type and choose Create.
    3. Pricing tire default chosen is Free, you’ll be able to maintain as it’s.
    4. Enter contact particulars
    5. As soon as it’s created, click on on handle to login to your sendgrid account
    How to Send Email Using SendGrid with Azure Function in .NET Core 

     

    In your SendGrid dashboard, choose Settings after which API Keys within the menu on the left.

     

    How to Send Email Using SendGrid with Azure Function in .NET Core

     

    Click on on Create API Key => Give API Key Identify => Click on on create and look at.

     

    How to Send Email Using SendGrid with Azure Function in .NET Core

     

    Now Copy the API Key worth from SendGrid account and add that into native.settings.json below values as like under

    1. “Values”: {  
    2.   “AzureWebJobsStorage”“UseDevelopmentStorage=true”,  
    3.   “StorageConnectionString”“UseDevelopmentStorage=true”,  
    4.   “FUNCTIONS_WORKER_RUNTIME”“dotnet”,  
    5.   “CloudStorageAccount”“DefaultEndpointsProtocol=https;AccountName=;AccountKey=;EndpointSuffix=core.home windows.internet”,  
    6.   “SendgridAPIKey”“Copy and paste the API Key worth from SendGrid”  
    7. }  

    Alright! Now we’re able to create a second operate which shall be a Queue set off operate.

     

    Queue set off operate to drag messages from the queue and ship an e-mail (second operate)

     

    As I already talked about, the aim of this operate is to course of queue and skim content material from the queue and ship emails as SendGridMessage.

     

    To do that , Proper click on on venture => Add new operate => Identify it as “SendGridEmailQueueTriggerFunction.cs” => Click on on Add => Choose Queue Set off operate sort => Click on on Create.

     

    Set up required NuGet packages into the operate app venture.

    • Microsoft.Azure.WebJobs.Extensions.SendGrid
    • Microsoft.Azure.WebJobs (Already put in as a part of the primary operate)
    • Microsoft.Azure.WebJobs.Extensions.Storage (Already put in as a part of the primary operate)

    Now delete the default content material of the operate and modify the operate accordingly. In operate parameter, specify the queue set off identify “email-queue”, Connection as Storage account connection string identify for studying the queue i.e. “CloudStorageAccount” which we already added in native settings Json in addition to azure operate app configuration as a part of first operate configuration.

     

    As we’ll use SendGrid as an e-mail sending consumer, Add [SendGrid(ApiKey = “SendgridAPIKey”)] out SendGridMessage sendGridMessage as extra prams – the place we’ll set SendGrid API Key identify and sendGridMessage object which we’ll set into the capabilities.

     

    SendGridEmailQueueTriggerFunction.cs 

    1. utilizing System;  
    2. utilizing System.IO;  
    3. utilizing Microsoft.Azure.Storage;  
    4. utilizing Microsoft.Azure.Storage.Blob;  
    5. utilizing Microsoft.Azure.WebJobs;  
    6. utilizing Microsoft.Extensions.Configuration;  
    7. utilizing Microsoft.Extensions.Logging;  
    8. utilizing Newtonsoft.Json;  
    9. utilizing Newtonsoft.Json.Linq;  
    10. utilizing SendGrid.Helpers.Mail;  
    11.   
    12. namespace AzFunctions  
    13. {  
    14.     public static class SendGridEmailQueueTriggerFunction  
    15.     {  
    16.         [FunctionName(“SendGridEmailQueueTriggerFunction”)]  
    17.         public static void Run([QueueTrigger(“email-queue”, Connection = “CloudStorageAccount”)]string myQueueItem,  
    18.             [SendGrid(ApiKey = “SendgridAPIKey”)] out SendGridMessage sendGridMessage,  
    19.             ILogger log)  
    20.         {  
    21.             log.LogInformation($“C# Queue set off operate processed: {myQueueItem}”);  
    22.   
    23.             strive  
    24.             {  
    25.                 var queueItem = myQueueItem.ToString();  
    26.   
    27.                 dynamic jsonData = JObject.Parse(queueItem);  
    28.                 string emailBody = jsonData.Content material;  
    29.   
    30.                 sendGridMessage = new SendGridMessage  
    31.                 {  
    32.                     From = new EmailAddress(“no-reply@myazureapp.com”“AzureFuncApps”),  
    33.                 };  
    34.                 sendGridMessage.AddTo(“youremailaddess@area.com”);  
    35.                 sendGridMessage.SetSubject(“Superior Azure Perform app”);  
    36.                 sendGridMessage.AddContent(“textual content/html”, emailBody);  
    37.             }  
    38.             catch (Exception ex )  
    39.             {  
    40.                 sendGridMessage = new SendGridMessage();  
    41.                 log.LogError($“Error occured whereas processing QueueItem {myQueueItem} , Exception – {ex.InnerException}”);  
    42.   
    43.             }   
    44.         }   
    45.     }  
    46. }  

    Just remember to added “SendgridAPIKey” config worth in native settings file.

    Now you’ll be able to check the operate domestically, if you need.

     

    To publish the operate app, right-clicking on the answer and click on on Publish. As soon as the deployment is profitable, you will note the newly created operate within the Azure portal below the operate app. Let’s add a brand new software setting “SendgridAPIKey” into the Azure operate app configuration.

     

    How to Send Email Using SendGrid with Azure Function in .NET Core

     

    Alright, now run the primary operate to push some information into the queue. If information are already there then the second operate will routinely choose up queue messages and set off e-mail.

     

    After the profitable execution of the second operate, you will note no queue messages are there in storage. Meaning all are processed.

     

    Let’s test the mailbox the place the e-mail has been triggered!

     

    How to Send Email Using SendGrid with Azure Function in .NET Core 

     

    Wonderful!

     

    We carried out e-mail notification utilizing the SendGrid account by the Azure queue set off operate.

     

    Observe

    In case of any processing error throughout e-mail sending, the queue merchandise will retry 5 instances. If it nonetheless failed, after which you will note a poison queue (referred to as email-queue-poison) created and all unprocessed queue objects had been moved there.

     

    Abstract

     

    On this article, we created an e-mail queue although azure HTTP set off operate and pushed some HTML content material as JSON object into the queue. And course of the e-mail queue by one other queue set off operate that pulls e-mail HTML content material and sends an e-mail to the recipient utilizing the SendGrid message. Primarily based in your want, you’ll be able to learn e-mail addresses from blob content material in addition to like we did for e-mail content material. I hope you discover this text helpful!

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button