Email management

How to Send Transactional Emails in a Spring Boot Application Using JAVA (JavaMailSender)? (with Codes)

Sanjeev Kumar
January 15, 2024
Learn efficient JavaMailSender usage in Spring Boot for seamless transactional email integration. Send emails, handle attachments, and enhance user experience using JAVA.
TABLE OF CONTENTS

After our comprehensive article on How to Send Transactional Emails With JAVA? (3 Methods With Codes - JavaMail API, Simple Java Mail & SuprSend), it's time to check JavaMailSender in more details coupled with a Spring Boot application. JavaMailSender is a key component in Spring Boot for handling email functionality. It simplifies the process of sending emails and integrates well with Spring applications. In this section, we'll provide an overview of the JavaMailSender interface and its importance in the Spring Boot ecosystem.

Pros and Cons of JavaMailSender

Provide a balanced overview of the advantages and disadvantages of using JavaMailSender for sending emails in a Spring Boot application.

Pros:

  • Well-structured and widely used in enterprise applications.
  • Comprehensive set of functionalities, including reading, composing, and sending emails.
  • Programmatic accessibility for integration with other programs.

Cons:

  • Extended compilation time due to the nature of JavaMail API.
  • Potential memory consumption issues when utilizing the Mail API.

Dependencies and Project Setup

Before diving into the code, it's essential to set up the project with the necessary dependencies. We'll guide you through the process of adding the spring-boot-starter-mail dependency in the pom.xml file and ensuring a proper project setup for email functionality.

```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
```

Implementation of Email Sending

Now, let's explore the practical implementation of sending emails in a Spring Boot application. We'll provide a detailed code walkthrough of a sample Spring Boot application that utilizes the JavaMailSender interface. The code will include:

  • Autowiring the JavaMailSender bean.
  • Creating a method to compose and send a simple email.
      
          @SpringBootApplication
          public class MailSenderApplication {

              @Autowired
              private JavaMailSender javaMailSender;

              public static void main(String[] args) {
                  SpringApplication.run(MailSenderApplication.class, args);
              }

              public void sendEmail() {
                  SimpleMailMessage message = new SimpleMailMessage();
                  message.setTo("recipient@example.com");
                  message.setSubject("Test Email");
                  message.setText("This is a test email sent from Spring Boot.");

                  javaMailSender.send(message);
              }
          }
        
    

HTML Email Content

Enhance your emails by sending HTML content. Modify the sendEmail method to include HTML content in the email body.

      
          public void sendHtmlEmail() {
              MimeMessage message = javaMailSender.createMimeMessage();
              MimeMessageHelper helper = new MimeMessageHelper(message, true);

              helper.setTo("recipient@example.com");
              helper.setSubject("HTML Email Test");
              helper.setText("

This is an HTML email sent from Spring Boot!

", true); javaMailSender.send(message); }

Adding Attachments

Extend your email functionality by adding attachments. Update the sendEmail method to include an attachment.

      
          public void sendEmailWithAttachment() {
              MimeMessage message = javaMailSender.createMimeMessage();
              MimeMessageHelper helper = new MimeMessageHelper(message, true);

              helper.setTo("recipient@example.com");
              helper.setSubject("Email with Attachment");
              helper.setText("This email contains an attachment.");

              // Add attachment
              FileSystemResource file = new FileSystemResource(new File("path/to/attachment.txt"));
              helper.addAttachment("Attachment.txt", file);

              javaMailSender.send(message);
          }
        
    

Error Handling

Address potential issues by implementing error handling in your email sending process.

      
          public void sendEmailWithExceptionHandling() {
              try {
                  SimpleMailMessage message = new SimpleMailMessage();
                  message.setTo("recipient@example.com");
                  message.setSubject("Test Email");
                  message.setText("This is a test email sent from Spring Boot.");

                  javaMailSender.send(message);
              } catch (MailException e) {
                  // Handle email sending exception
                  e.printStackTrace();
              }
          }
        
    

Alternative Method: Using SuprSend - Third-Party Multichannel Notification Infrastructure with JAVA SDKs

A third-party multichannel notification infrastructure provider, such as SuprSend, presents an avenue for sending cross-channel notifications through a unified API, covering various channels like Emails, SMS, and Push Notifications. SuprSend streamlines the notification flow by managing all relevant channels and providers seamlessly through a single API, eliminating the need for extensive coding.

Key Features & Benefits:

  1. Extensive Integration Options: Seamless integration with 50+ Communication Service Providers (CSPs) and across 6+ communication channels, like Mixpanel, Segment, Twilio, Mailchimp, Slack, Teams, SNS, Vonage, Whatsapp and more.
  2. No Tech Dependency: End-to-end notification management without involving the engineering team, optimizing their productivity. Just integrate the JAVA SDK once, and your product team will manage everything else.
  3. Intelligent Routing: Create and implement intelligent cross-channel flows across providers without technical dependencies.
  4. In-App SDK: Provides a fully loaded, developer-ready in-app layer for both web and mobile applications.
  5. Granular Template Management: Utilize an intuitive drag & drop editor for designing templates, offering superior control over the content.
  6. Powerful Workspace: Efficiently manage various projects with distinct integrations, workflows, and templates in each workspace.
  7. Unified Analytics: Track, measure, and make data-driven decisions with a unified view of cross-channel analytics across vendors.
  8. Smart Automation: Automate synchronization, refreshing, and notification triggers, allowing more focus on critical tasks.
  9. Quick Scalability: SuprSend automates scalability, putting it on autopilot for a hassle-free experience.

Cons:

  1. Cost Considerations: Managing multiple notification channels may incur costs. Monthly Notification Limits:
  2. Be mindful of limitations on the maximum number of notifications receivable per month.

Designed with a "developer-first" approach, SuprSend handles the heavy lifting, enabling engineering teams to concentrate on their tasks without the added complexity of managing notifications.

Getting Started with SuprSend for Sending emails in JAVA:

Step I: Log in to the SuprSend Account.

Image description

Step II: Integrate with Email(s).

  • SuprSend provides a ready-to-integrate provider list for emails, including AWS SES, Mailchimp (Mandrill), Mailgun, Netcore, Outlook, Postmark, SendGrid, and more.
  • After logging in, navigate to the integration section, choose the desired email channel, and enter the necessary information.
Image description

Step III: Create & Load Template.

  • SuprSend allows you to create and store messaging content with a user-friendly drag & drop editor. To create a template, head to the "Templates" tab, click "Create," and then utilize the "Drag & Drop Editor" for customization.
Image description

Step IV: Create Smart Flow (Routing).

  • Define rules and logic effortlessly by heading to the "Workflows" tab. Choose "Single Channel" and create a flow by adding basic details and logic conditions.
  • Combine templates, providers, routes, and channels to fire notifications.
Image description

Step V: Trigger a Notification Event via API
Following this step, we'll integrate the SuprSend API into our Java application. Begin by updating the Maven pom.xml file with the provided dependency and execute mvn compile to download the necessary components. More info in documentation.

        
            <dependencies>
              <dependency>
                <groupId>com.suprsend</groupId>
                <artifactId>suprsend-java-sdk</artifactId>
                <version>0.5.0</version>
              </dependency>
            </dependencies>
        
    


Sample Code to call Suprsend backend using SDK and trigger workflows.

        
            package tests;

            import java.io.File;
            import java.io.FileInputStream;
            import java.io.FileNotFoundException;
            import java.io.InputStream;

            import org.json.JSONObject;
            import org.json.JSONTokener;

            import suprsend.Suprsend;

            public class TestSuprsendSDK {

                private JSONObject loadBody(String fileName) throws FileNotFoundException {
                    JSONObject jsonObject;
                    String relativePath = String.format("%s/src/%s/resources/%s.json", System.getProperty("user.dir"),
                            this.getClass().getPackage().getName(), fileName);
                    InputStream schemaStream = new FileInputStream(new File(relativePath));
                    jsonObject = new JSONObject(new JSONTokener(schemaStream));
                    return jsonObject;
                }

                public static void main(String[] args) throws Exception {
                    TestSuprsendSDK sdk = new TestSuprsendSDK();
                    // Load workflow body json
                    JSONObject body = sdk.loadBody("input");
                    // SDK instance
                    Suprsend suprsend = new Suprsend("WORKSPACE KEY", "WORKSPACE KEY");
                    Workflow wf = new Workflow(body, idempotencyKey, brandId)

                    // Trigger workflow
                    JSONObject resp = suprClient.triggerWorkflow(wf);
                    System.out.println(resp);
                }

            }}
        
    


Step VI: Check Event Analytics And Logs.

  • Gain granular channel-wise and vendor-wise analytics through the unified dashboard. View "Event Analytics" for actionable insights and access detailed logs through the "Logs" tab. Explore more about logs.
Image description

Conclusion:

In conclusion, sending emails in a Spring Boot application using the JavaMailSender interface is a straightforward and efficient process. By following the steps outlined in this article, you can seamlessly integrate email functionality into your Spring Boot projects, facilitating communication with users and enhancing the overall user experience.

Written by:
Sanjeev Kumar
Engineering, SuprSend
ABOUT THE AUTHOR

What’s a Rich Text element?

The rich text element allows you to create and format headings, paragraphs, blockquotes, images, and video all in one place instead of having to add and format them individually. Just double-click and easily create content.

Static and dynamic content editing

A rich text element can be used with static or dynamic content. For static content, just drop it into any page and begin editing. For dynamic content, add a rich text field to any collection and then connect a rich text element to that field in the settings panel. Voila!

How to customize formatting for each rich text

Headings, paragraphs, blockquotes, figures, images, and figure captions can all be styled after a class is added to the rich text element using the "When inside of" nested selector system.

Implement a powerful stack for your notifications
By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. View our Privacy Policy for more information.