How to Send Bulk Emails at Scheduled Times Using Azure Functions and SendGrid with Java

Sending bulk emails on a scheduled time can be a crucial feature for many applications. Using Azure Functions along with SendGrid can help you automate this process with ease. In this guide, we will walk you through the steps to send bulk emails asynchronously at a scheduled time using Java, Azure, and SendGrid.



Prerequisites

Before we dive into the implementation, ensure you have the following prerequisites:

  • Azure Account: Sign up for an Azure account if you don’t have one already.
  • SendGrid Account: Create an account and obtain your SendGrid API Key.
  • Java Development Environment: Make sure you have an IDE such as IntelliJ IDEA or Eclipse set up with a Maven/Gradle project.
  • Azure Functions Core Tools: If you’re developing locally, you need to install the Azure Functions Core Tools.

Step 1: Install Required Dependencies

  1. Set up Maven Dependencies: Add the following dependencies to your pom.xml file to integrate Azure Functions and SendGrid into your Java project.

    <dependencies>
        <!-- Azure Functions Dependency -->
        <dependency>
            <groupId>com.microsoft.azure.functions</groupId>
            <artifactId>azure-functions-java-library</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- SendGrid Java SDK -->
        <dependency>
            <groupId>com.sendgrid</groupId>
            <artifactId>sendgrid-java</artifactId>
            <version>4.10.3</version>
        </dependency>
    </dependencies>
    
  2. Install SendGrid Java SDK: The SendGrid library allows you to interact with the SendGrid API to send emails programmatically.


Step 2: Create the Azure Timer-Triggered Function

  1. Create a New Azure Function: We will use the Timer Trigger to execute our function at a scheduled time (e.g., every day at 9 AM).

  2. Write the Timer-Triggered Function: In your BulkEmailFunction.java file, add the following code:

    import com.microsoft.azure.functions.annotation.*;
    import com.microsoft.azure.functions.*;
    import com.sendgrid.*;
    
    import java.io.IOException;
    
    public class BulkEmailFunction {
        @FunctionName("BulkEmailFunction")
        public void run(
            @TimerTrigger(name = "timerInfo", schedule = "0 0 9 * * *") // Every day at 9 AM
            String timerInfo,
            final ExecutionContext context
        ) throws IOException {
            context.getLogger().info("Bulk email function triggered");
    
            // SendGrid API Key
            String sendGridApiKey = System.getenv("SENDGRID_API_KEY");
    
            // Initialize SendGrid
            SendGrid sg = new SendGrid(sendGridApiKey);
            Request request = new Request();
    
            // Prepare Email Data
            Email from = new Email("your-email@example.com");
            String subject = "Bulk Email Subject";
            Email to = new Email("recipient@example.com");
            Content content = new Content("text/plain", "Hello, this is a bulk email!");
            Mail mail = new Mail(from, subject, to, content);
    
            // Add multiple recipients
            mail.personalization.get(0).addTo(new Email("another-recipient@example.com"));
            mail.personalization.get(0).addTo(new Email("third-recipient@example.com"));
    
            // Send Email
            try {
                request.setMethod(Method.POST);
                request.setEndpoint("mail/send");
                request.setBody(mail.build());
                Response response = sg.api(request);
                context.getLogger().info("Response: " + response.getStatusCode());
            } catch (IOException ex) {
                context.getLogger().severe("Error sending email: " + ex.getMessage());
                throw ex;
            }
        }
    }

    In this code:

    • The function is triggered by a timer (set to run every day at 9 AM).
    • The SendGrid API key is used to authenticate and send emails.
    • The email contains a subject, body, and multiple recipients.

Step 3: Set Up SendGrid API Key in Azure

  1. Obtain SendGrid API Key:

    • Log in to your SendGrid account.
    • Navigate to Settings > API Keys.
    • Generate a new API key and store it securely.
  2. Add SendGrid API Key to Azure Function:

    • In the Azure portal, go to your Function App.
    • Under Configuration > Application Settings, add a new setting for SENDGRID_API_KEY and paste the API key.

Step 4: Deploy the Function to Azure

  1. Package the Function: Once your function code is ready, build the project using Maven:

    mvn clean package
  2. Deploy the Function: Deploy the function to Azure using Azure CLI:

    az functionapp deployment source config-zip --src <path-to-zip> --name <function-app-name> --resource-group <resource-group>
    

Step 5: Verify Email Delivery

  1. Monitor Function Logs:

    • Go to your Azure Function App in the portal and check the Monitor tab to ensure the function executes correctly at the scheduled time.
  2. Check Email Delivery:

    • Verify that emails are being sent to the specified recipients at the scheduled time.

By following these steps, you can set up an Azure Function with a Timer Trigger to send bulk emails at a scheduled time using SendGrid. This solution is highly scalable and can be adapted to various business use cases requiring scheduled email delivery.

Benefits of Using Azure Functions for Scheduled Bulk Emails:

  • Cost-Efficient: Azure Functions follows a pay-per-use pricing model, meaning you only pay for execution time.
  • Scalability: Azure Functions can scale automatically to handle more email requests if needed.
  • Security: Secure integration with SendGrid using API keys and environment variables for sensitive data management.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete