Do you want to send emails in an Azure WebJob? In a simple scenario we will discover how to do it with SendGrid.

When you need to send emails from an Azure WebJob, the following extension is very helpful:

WebJobs SendGrid extension

Today we will take a look at the version 2.0 that came along with the release of the Azure WebJobs SDK 2.0.

 

In this article, we will discover how to send a simple email from an Azure WebJob with the SenGrid extension. As a base, we will create a project with the Azure WebJob template in Visual Studio.

 

Creation

The first thing you will need is to add the following NuGet package to your project: Microsoft.Azure.WebJobs.Extensions.SendGrid

 

To enable the SendGrid extension in your WebJob you will need to configure the JobHostConfiguration like the following:

using Microsoft.Azure.WebJobs;

namespace AzureWebJobs.SendGridExtension
{
	// To learn more about Microsoft Azure WebJobs SDK, please see https://go.microsoft.com/fwlink/?LinkID=320976
	class Program
	{
		// Please set the following connection strings in app.config for this WebJob to run:
		// AzureWebJobsDashboard and AzureWebJobsStorage
		static void Main()
		{
			var config = new JobHostConfiguration();

			if (config.IsDevelopment)
			{
				config.UseDevelopmentSettings();
			}

			config.UseSendGrid();

			var host = new JobHost(config);
			// The following code ensures that the WebJob will be running continuously
			host.RunAndBlock();
		}
	}
}

The important part here is to call the extension named UseSendGrid. This will enable the SendGrid extension.

 

We will now add a new application settings to be able to connect to SendGrid:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <!-- The format of the connection string is "DefaultEndpointsProtocol=https;AccountName=NAME;AccountKey=KEY" -->
    <!-- For local execution, the value can be set either in this config file or through environment variables -->
    <add name="AzureWebJobsDashboard" connectionString="" />
    <add name="AzureWebJobsStorage" connectionString="" />
  </connectionStrings>
  <appSettings>
    <add key="AzureWebJobsSendGridApiKey" value="" />
  </appSettings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Azure.KeyVault.Core" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.WindowsAzure.Storage" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-8.1.1.0" newVersion="8.1.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

 

Now using the default ProcessQueueMessage function that uses a QueueTrigger, we want to send an email when a message is added to the queue:

using System.IO;
using Microsoft.Azure.WebJobs;
using SendGrid.Helpers.Mail;

namespace AzureWebJobs.SendGridExtension
{
	public class Functions
	{
		// This function will get triggered/executed when a new message is written 
		// on an Azure Queue called queue.
		public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log, [SendGrid(From = "no-reply@anydomainxyz.com", To = "anybody@anydomainxyz.com")] out Mail mail)
		{
			log.WriteLine(message);

			mail = new Mail();

			mail.Subject = "WebJob - Queue message processed successfully";
			mail.AddContent(new Content("text/plain", $"The message '{message}' was successfully processed."));
		}
	}
}

You can notice several things here:

 

Example of use

Once the WebJob ready and properly configured, we will launch it and add a message to the queue:

Found the following functions:
AzureWebJobs.SendGridExtension.Functions.ProcessQueueMessage
Job host started
Executing 'Functions.ProcessQueueMessage' (Reason='New queue message detected on 'queue'.', Id=ef4a15bf-ce79-4be1-8b56-a3237b929b50)
My queue test message
Executed 'Functions.ProcessQueueMessage' (Succeeded, Id=ef4a15bf-ce79-4be1-8b56-a3237b929b50)

If everything goes well, you should see the same kind of message in console output as above.

You should also receive an email to the address you've specified in the To property of the SendGrid attribute. The title will be as WebJob - Queue message processed successfully, and the body will contain the message coming from the queue like the following: The message ‘My queue test message’ was successfully processed.

 

To go further

If you want to send more than one email, we can use the WebJob IAsyncCollector like the following:

public static async Task ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log, [SendGrid(From = "no-reply@anydomainxyz.com", To = "anybody@anydomainxyz.com")] IAsyncCollector mails)

There are many other ways to send emails from the extension, more details can be found here:

SendGrid Extension Samples

 

 

Summary

We have seen how to send emails from an Azure WebJob using the SendGrid extension.

 

You can download the example solution here:

Download full sources

Or

Browse the GitHub repository

(Note that the project uses Microsoft.Azure.WebJobs version 2.0.0)

 

Please feel free to comment or contact me if you have any question about this article.

Add a comment

(Will not be published)

Back to articles