Sending an email notification using SendGrid service
In this recipe, we will learn how to create a SendGrid output binding and send an email notification, containing static content, to the website administrator. Since our use case involves just one administrator, we will be hard-coding the email address of the administrator in the To address field of the SendGrid output (message) binding.
Getting ready
We'll perform the following steps before moving on to the next section:
- We will create a SendGrid account API key from the Azure portal.
- We will generate an API key from the SendGrid portal.
- We will configure the SendGrid API key with the Azure Function app.
Creating a SendGrid account API key from the Azure portal
In this section, we'll be creating a Send service and also generate the API by performing the following steps:
- Navigate to the Azure portal and create a SendGrid Email Delivery account by searching for it in the marketplace, as shown in Figure 2.2:
Figure 2.2: Searching for SendGrid Email Delivery in the marketplace
- In the SendGrid Email Delivery blade, click on the Create button to navigate to Create SendGrid Account. Select Free in the Pricing Tier options, provide all the other details, and then click on the Review + Create button to review this information. Finally, click on the Create button, as shown in Figure 2.3:
Figure 2.3: Creating a SendGrid email delivery account
Note
At the time of writing, the SendGrid free account allows you to send 25,000 free emails per month. If you would like to send more emails, then you can review and change the pricing plans based on your needs.
- Make a note of the password entered in the previous step. Once the account is created successfully, navigate to SendGrid Account. You can use the search box available at the top.
SendGrid is not a native Azure service. So, we need to navigate to the SendGrid website to generate the API key. Let's learn how to do that next.
Generating credentials and the API key from the SendGrid portal
Let's generate the API key by performing the following steps:
- In order to utilize the SendGrid account in the Azure Functions runtime, we need to provide the SendGrid credentials as input for Azure Functions. You can generate those details from the SendGrid portal. Let's navigate to the SendGrid portal by clicking on the Manage button in the Essentials blade of SendGrid Account, as shown in Figure 2.4:
Figure 2.4: Acquiring SendGrid credentials in the Manage blade
- In the SendGrid portal, click on the Account Details menu under Settings and copy the username, as shown in Figure 2.5:
Figure 2.5: Copying the SendGrid credentials
- In the SendGrid portal, the next step is to generate the API keys. Now, click on API Keys under the Settings section of the left-hand side menu, as shown in Figure 2.6:
Figure 2.6: Generating API keys
- On the API Keys page, click on Create API Key, as shown in Figure 2.7:
Figure 2.7: Creating API keys
- In the Create API Key pop-up window, provide a name and choose API Key Permissions, and then click on the Create & View button.
- After a moment, you will be able to see the API key. Click on the key to copy it to the clipboard, as shown in Figure 2.8:
Figure 2.8: Copying the API key
Having copied the API key, we'll now configure it.
Configuring the SendGrid API key with the Azure Function app
Let's now configure the SendGrid API key by performing the following steps:
- Create a new App settings configuration in the Azure Function app by navigating to the Configuration blade, under the Platform features section of the function app, as shown in Figure 2.9:
Figure 2.9: Creating a new app setting configuration
- Click on the Save button after adding the App settings from the preceding step.
How to do it...
In this section, we will perform the following tasks:
- We will create a storage queue binding to the HTTP trigger.
- We will create a queue trigger to process the message of the HTTP trigger.
- We will create a SendGrid output binding to the queue trigger.
Creating a storage queue binding to the HTTP trigger
Let's create the queue bindings now. This will allow us to create a message to be added to the queue.
Perform the following steps:
- Navigate to the Integrate tab of the RegisterUser function and click on the New Output button to add a new output binding.
- Choose Azure Queue Storage and click on the Select button to add the binding and provide the values shown in Figure 2.10, and then click on the Save button. Please make a note of the Queue name (in this case, notificationqueue), which will be used in a moment:
Figure 2.10: Adding a new output binding
- Navigate to the Run method of the RegisterUser function and make the following highlighted changes. You added another queue output binding and added an empty message to trigger the queue trigger function. For now, you have not added a message to the queue. We will make changes to the NotificationQueueItem.AddAsync(""); method in the Sending an email notification dynamically to the end user recipe of the chapter:
public static async Task<IActionResult> Run(
HttpRequest req,
CloudTable objUserProfileTable,
IAsyncCollector<string> objUserProfileQueueItem,
IAsyncCollector<string> NotificationQueueItem,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string firstname=null,lastname = null;
...
...
await NotificationQueueItem.AddAsync("");
return (lastname + firstname) != null
? (ActionResult)new OkObjectResult($"Hello, {firstname + " " + lastname}")
: new BadRequestObjectResult("Please pass a name on the query" + "string or in the request body");
}
Let's now proceed to create the queue trigger.
Creating a queue trigger to process the message of the HTTP trigger
In this section, you'll learn how to create a queue trigger by performing the following steps:
- Create an Azure Queue Storage Trigger by choosing the template shown in Figure 2.11:
Figure 2.11: Creating an Azure Queue Storage Trigger
- In the next step, provide the name of the queue trigger and provide the name of the queue that needs to be monitored for sending the notifications. Once you have provided all the details, click on the Create button to create the function:
Figure 2.12: Creating a new function
- After creating the queue trigger function, run the RegisterUser function to see whether the queue trigger is being invoked. Open the RegisterUser function in a new tab and test it by clicking on the Run button. In the Logs window of the SendNotifications tab, you should see something similar to Figure 2.13:
Figure 2.13: Invoking the queue trigger by running the RegisterUser function
Once we have ensured that the queue trigger is working as expected, we need to create the SendGrid bindings to send the email in the following section.
Creating a SendGrid output binding to the queue trigger
Perform the following steps to create the SendGrid output bindings to send the email:
- Navigate to the Integrate tab of the SendNotifications function and click on the New Output button to add a new output binding.
- Choose the SendGrid binding and click on the Select button to add the binding.
- The next step is to install the SendGrid extensions (these are packages related to SendGrid). Click on the Install button to install the extensions if prompted, as shown in Figure 2.14. It might take a few minutes to install the extensions:
Figure 2.14: Notification to install extensions in the SendGrid bindings
Note
If there is no prompt notification, please delete the output binding and recreate it. You could also install the extensions manually by going through the instructions mentioned in https://docs.microsoft.com/azure/azure-functions/install-update-binding-extensions-manual.
- Provide the following parameters in the SendGrid output (message) binding:
- Message parameter name: Leave the default value, which is message. We will be using this parameter in the Run method in a moment.
- SendGrid API Key: Choose the App settings key that you created in the Configuration blade for storing the SendGrid API Key.
- To address: Provide the email address of the administrator.
- From address: Provide the email address from where you would like to send the email. This might be something like donotreply@example.com.
- Message subject: Provide the subject that you would like to have displayed in the email subject.
- Message Text: Provide the email body text that you would like to have in the body of the email.
This is how the SendGrid output (message) binding should appear after providing all the fields:
Figure 2.15: Adding details in the SendGrid output (message) binding
- Once you review the values, click on Save to save the changes.
- Navigate to the Run method of the SendNotifications function and make the following changes:
- Add a new reference for SendGrid, along with the SendGrid.Helpers.Mail namespace.
- Add a new out parameter message of the SendGridMessage type.
- Create an object of the SendGridMessage type. We will look at how to use this object in the next recipe, Sending an email notification dynamically to the end user.
- The following is the complete code of the Run method:
#r "SendGrid"
using System;
using SendGrid.Helpers.Mail;
public static void Run(string myQueueItem,out SendGridMessage message, ILogger log)
{
log.LogInformation($"C# Queue trigger function processed:
{myQueueItem}");
message = new SendGridMessage();
}
- Now, let's test the functionality of sending the email by navigating to the RegisterUser function and submitting a request with some test values, as follows:
{
"firstname": "Bill",
"lastname": "Gates",
"ProfilePicUrl":"URL Here"
}
How it works...
The aim of this recipe is to send an email notification to the administrator, updating them that a new registration was created successfully.
We have used one of the Azure function output bindings, named SendGrid, as a Simple Mail Transfer Protocol (SMTP) server for sending our emails by hard-coding the following properties in the SendGrid output (message) bindings:
- The "from" email address
- The "to" email address
- The subject of the email
- The body of the email
The SendGrid output (message) bindings will use the API key provided in the App settings to invoke the required APIs of the SendGrid library in order to send the emails.