Broadleaf Microservices
  • v1.0.0-latest-prod

Using a Gmail Account To Send Emails with Broadleaf Notification Service

Overview

Broadleaf provides out of box configuration and helper classes that can be used for applications that want to use JavaMail.

A specific example is provided that can be used with Gmail.

Configuring the JavaMailMessageSender with JavaMail and GMAIL

The Broadleaf JavaMailMessageSender, requires you to configure and inject a javax.mail.JavaMailSender component which will typically involve leveraging Spring’s JavaMailSenderImpl.

Broadleaf provides a helper class for configuring for Gmail. See GmailJavaMailSeender.

This example shows how to configure for Gmail. Other standard JavaMail configurations can be used with Broadleaf and would be configured similarly.

import org.springframework.context.annotation.*;
import com.broadleafcommerce.notification.service.*;
import com.broadleafcommerce.notification.service.integration.GmailJavaMailSender;

@Configuration
public class MyNotificationConfiguration {

    // Step 1: Configure a JavaMailSender
    @Bean
    GmailJavaMailSender gmailJavaMailSender() {
        // Example seetings for sending from a gmail account
        String login = "senderusername@gmail.com";
        String password = "passwordForAccount";
        return new GmailJavaMailSender(username, password);
    }

    // Step 2: Configure a Broadleaf JavaMailMessageSender
    @Bean
    JavaMailMessageSender broadleafJavaMailMessageSender(GmailJavaMailSender javaMailSender) {
        return new JavaMailMessageSender(javaMailSender);
    }

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

About the example

The above configuration uses the ThymeleafMessageBuilder. Thymeleaf provides capabilities to provide rich html emails based on templates. 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.

Note
Using the Gmail configuration can be good for local testing and low volume needs. See the Google documentation for up to date information and be aware that personal Gmail accounts have limits on sending messages that will make them inappropriate for most commerce needs.