Broadleaf Microservices
  • v1.0.0-latest-prod

Using SendGrid To Send Emails with Broadleaf Notification Service

SendGrid is a leading provider for sending emails. Broadleaf provides an out of box implementation for transaction emails that can be configured with your SendGrid account.

See the Send Grid Website for more information on SendGrid and to obtain an account and credentials.

Configuring the SendGridMessageSender

To use the out of box SendGrid configuration, add the following configuration to your SpringBoot application that is running the NotificationService.

import org.springframework.context.annotation.*;
import com.broadleafcommerce.notification.service.*;
import com.broadleafcommerce.notification.service.integration.SendGridMessageSender;
import com.sendgrid.Email;

@Configuration
public class MyNotificationConfiguration {

    // Step 1: Configure a SendGridMessageSender
    @Bean
    SendGridMessageSender sendGridMessageSender() {
        // Obtain an apiKey from SendGrid
        String apiKey = "yourAPIKey";
        Email senderEmail = new Email("sender@yourcompany.com", "Sender Name");

        // Initialize the SendGridSender
        return new SendGridMessageSender(apiKey,senderEmail);
    }

    // Step 2: Register an EMAIL handler with the NotificationService
    @Bean
    NotificationHandler emailNotificationHandler(ThymeleafMessageBuilder builder,
            SendGridMessageSender sender) {
        return new DefaultNotificationHandler(builder, sender);
    }
}

About the example

The above configuration uses the ThymeleafMessageBuilder. Thymeleaf provides capabilities to provide rich html emails. Refer to MessageBuilders for more information.

To apply, the configuration must be component scanned by your application. A typical approach is to add the configurations to SpringBoot’s META-INF/spring.factories file.

Doing more with SendGrid

SendGrid has additional capabilities beyond the default implementation. These can be leveraged by extending the out of box SendGridMessageSender or creating your own implmentation of MessageSender. See the code for SendGridMessageSender as an example for creating a custom message sender.

In some cases, it could make sense to also build a custom NotificationHandler or MessageBuilder components.`