Building an Azure Queue Trigger Function for Sending Emails with Nodemailer

Introduction

In today's digital age, automated processes are essential for improving efficiency and productivity. One such automation is sending emails based on events or triggers. In this blog post, we'll explore how to create an Azure Queue Trigger Function using Node.js and Nodemailer to send emails when a message is added to an Azure Storage Queue.

Prerequisites

Before we dive into the code, make sure you have the following prerequisites in place.

  1. Azure account: Create a free Azure account if you don't have one.
  2. Azure Storage Account: Set up an Azure Storage Account to store the queue messages.
  3. Node.js and npm: Install Node.js and npm on your development machine.
  4. Visual Studio Code (or any preferred code editor).

Step 1. Create an Azure Queue Storage: Begin by creating an Azure Storage Account if you haven't already. Inside the Storage Account, create a queue named "mail-trigger." This queue will be used to trigger the Azure Function whenever a message is added.

Step 2. Set up your Azure Function App: Create an Azure Function App in the Azure portal. Make sure to select the Node.js runtime. Once created, navigate to the "Functions" section and add a new function. Choose the "Queue trigger" template and set the queue name to "mail-trigger."

Step 3. Configure local.settings.json: In your function app folder, create a file named local.settings.json to store local development settings. Update the file with your Azure Storage Account connection string, account name, and key. Also, specify the queue name and Node.js as the runtime.

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "YOUR_STORAGE_CONNECTION_STRING",
    "QUEUE_NAME": "mail-trigger",
    "ACCOUNT_NAME": "YOUR_STORAGE_ACCOUNT_NAME",
    "ACCOUNT_KEY": "YOUR_STORAGE_ACCOUNT_KEY",
    "FUNCTIONS_WORKER_RUNTIME": "node"
  }
}

Step 4. Configure host.json: In the same folder, create a file named host.json and configure it with the necessary settings for application insights and extensions.

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[3.*, 4.0.0)"
  },
  "concurrency": {
    "dynamicConcurrencyEnabled": true,
    "snapshotPersistenceEnabled": true
  }
}
  • Version: Indicates the version of the Azure Functions runtime. In this case, it's version "2.0."
  • logging: Configures logging settings for the Azure Functions application.
  • applicationInsights: Configures Application Insights integration for logging and monitoring.
  • samplingSettings: Specifies settings for log sampling.
  • isEnabled: Enables or disables log sampling. If true, log sampling is enabled.
  • excludedTypes: Specifies log types to exclude from sampling. In this case, "Request" logs are excluded.
  • extensionBundle: Configures the Azure Functions extension bundle.
  • id: Specifies the ID of the extension bundle.
  • version: Specifies the version range of the extension bundle to use. In this case, it's set to a range from version 3.x to version 4.0.0.
  • concurrency: Configures concurrency settings for the Azure Functions application.
  • dynamicConcurrencyEnabled: Enables or disables dynamic concurrency, allowing the system to adjust concurrency levels based on demand.
  • snapshotPersistenceEnabled: Enables or disables snapshot persistence, which helps maintain the state between function executions.

Step 5. Configure function.json: Update the function.json file to specify the queue trigger binding.

{
  "bindings": [
    {
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "mail-trigger",
      "connection": "AzureWebJobsStorage"
    }
  ]
}

Step 6. Write the Azure Queue Trigger Function Code: Now, create a file named index.js and implement the Azure Queue Trigger Function using Nodemailer.

const nodemailer = require("nodemailer");

module.exports = async function (context, myQueueItem) {
  context.log("JavaScript queue trigger function processed work item", myQueueItem);
  const transporter = nodemailer.createTransport({
    host: "smtp.office365.com",
    port: 587,
    ssl: true,
    tls: true,
    auth: {
      user: "[email protected]",
      pass: "***********",
    },
  });

  const mailOptions = {
    from: "[email protected]",
    to: myQueueItem,
    subject: "Test Email",
    text: "Hello, this is a test email from Node.js using Nodemailer!",
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.error("Error sending email:", error);
    } else {
      console.log("Email sent:", info.response);
    }
  });
};

The code has been finalized. Please execute it by pressing F5,

Terminal

Proceed by initiating the function, and then include your email address in the Azure Queue Storage.

Queue

Now, verify that your function app is receiving your email ID from the queue storage.

Function triggered

The function has been successfully triggered. Please check your email for the message sent from the function app.

Test mail

Step 7. Deploy your function app to Azure using Visual Studio Code or your preferred deployment method. Once deployed, add a message to the "mail-trigger" queue in the Azure Storage Account. Check the Azure Function logs to see the processing details and verify the email sent to the specified address.

Conclusion

Well done! You have successfully developed an Azure Queue Trigger Function using Node.js and Nodemailer for sending emails triggered by messages in an Azure Storage Queue. This implementation offers versatility for handling diverse automation scenarios within your applications. Delve into additional Azure services and features to further augment and refine your automated workflows. If you have any questions or concerns, please feel free to share them in the comments section.


Similar Articles