DEV Community

Cover image for How to Send Email Notifications using JAVA? (3 Methods With Code Examples)
Nik L. for SuprSend

Posted on • Updated on • Originally published at suprsend.com

How to Send Email Notifications using JAVA? (3 Methods With Code Examples)

Some of our articles:

  1. Building a Scalable Notification System with gRPC and Microservices
  2. How to Send Email Notifications using Python? (With Code Examples)
  3. A Complete Guide on Notification Infrastructure for Modern Applications in 2023

Method 1: Using JavaMail API

Overview:

JavaMail API, a platform-independent and protocol-independent framework, empowers Java client applications for comprehensive email and messaging functionalities. Its generic interface provides abstract classes containing objects created in the transactional email system. You can also check how to send transactional emails in a spring boot application using JAVA.

Pros:

  1. Well-structured and Widely Used:

    • JavaMail API is known for its robust structure and widespread adoption, particularly in enterprise applications.
  2. Versatility in Functionality:

    • Offers a comprehensive set of functionalities, including reading, composing, and sending emails.
  3. Programmatic Accessibility:

    • Facilitates integration with other programs, simplifying the process of sending mail confirmations or other messages.

Cons:

  1. Extended Compilation Time:

    • Developers might experience longer code compilation times due to the nature of JavaMail API.
  2. Memory Consumption:

    • Utilizing the Mail API may lead to a significant consumption of JAVA heap space.

Demonstration:

Step 1: Installing JavaMail API

  • Inclusion of JAR files (mail.jar and activation.jar) in the CLASSPATH.
  • Setting up an SMTP server (e.g., Pepipost) for email transmission.

Step 2: Getting the Mail Session

  • Obtain a session object with host information using javax.mail.Session class.
Properties properties = new Properties(); // properties object contains host information
Session session = Session.getDefaultInstance(properties, null);
Enter fullscreen mode Exit fullscreen mode
  • Alternatively:
Properties properties = new Properties(); // properties object contains host information 
Session session = Session.getInstance(properties, null);
Enter fullscreen mode Exit fullscreen mode
  • Authentication for a network connection:
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
  protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("sender@gmail.com", "password");
  }
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Composing the Email

  • Utilize javax.mail.internet.MimeMessage subclass to configure sender, receiver, subject, and message body.
MimeMessage message = new MimeMessage(session);
// Sender email
message.setFrom(new InternetAddress(from));
// Receiver email
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Email subject
message.setSubject("This is the email subject");
// Email body
message.setText("This is the email body");
Enter fullscreen mode Exit fullscreen mode

Step 4: Adding Attachments

  • For including attachments, create a Multipart object and add a BodyPart for each attachment.
Multipart multipart = new MimeMultipart();

// Create a BodyPart for the main email content
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is the email body");

// Add the main content BodyPart to the Multipart
multipart.addBodyPart(messageBodyPart);

// Create a BodyPart for the attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource("path/to/attachment.txt"); // Replace with the actual file path
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("attachment.txt");

// Add the attachment BodyPart to the Multipart
multipart.addBodyPart(messageBodyPart);

// Set the Multipart as the message content
message.setContent(multipart);
Enter fullscreen mode Exit fullscreen mode

Step 5: Sending the Email

  • Employ the javax.mail.Transport class to send the email.
Transport.send(message);
Enter fullscreen mode Exit fullscreen mode

Complete Code Example:

// Import statements and package declaration

public class SendMail {
    public static void main(String[] args) {
      // Email details
      String to = "receiver@gmail.com";
      String from = "sender@gmail.com";
      String host = "smtp.gmail.com";

      // System properties and configuration
      Properties properties = System.getProperties();
      properties.put("mail.smtp.host", host);
      properties.put("mail.smtp.port", "465");
      properties.put("mail.smtp.ssl.enable", "true");
      properties.put("mail.smtp.auth", "true");

      // Session setup with authentication
      Session session = Session.getInstance(properties, new javax.mail.Authenticator(){
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication("sender@gmail.com", "password");
        }
      });

      try {
        // Creating and configuring the MimeMessage
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject("Your email subject goes here");

        // Adding Attachments
        Multipart multipart = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("You have a new message");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource("path/to/attachment.txt"); // Replace with the actual file path
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("attachment.txt");
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        // Sending the email
        Transport.send(message);
      } catch (MessagingException mex) {
        mex.printStackTrace();
      }
   }
}
Enter fullscreen mode Exit fullscreen mode

Method 2: Using Simple Java Mail

Overview:

Simple Java Mail, a user-friendly mailing library, presents a straightforward API for sending SMTP emails in Java. It serves as a wrapper around the JavaMail API, simplifying the email sending process by eliminating several classes and properties.

Pros:

  1. Robust, Small, and Lightweight:

    • Simple Java Mail boasts robustness while maintaining a small and lightweight footprint (134kB).
  2. Strict RFC Compliance:

    • Complies with all RFCs, ensuring compatibility with various email clients.
  3. Authenticated SOCKS Proxy Support:

    • Unique capability to send emails through an authenticated SOCKS proxy.
  4. Advanced Features:

    • Provides support for HTML, images, and attachments.
    • Allows sending emails to multiple receivers simultaneously.

Cons:

  1. Community Support Considerations:
    • The community support for Simple Java Mail may be relatively smaller compared to JavaMail API.

Demonstration:

Sending Enhanced Emails with Simple Java Mail

Sending emails using Simple Java Mail is a straightforward process. Extend its capabilities by incorporating HTML content and attachments:

  1. Create an Email Object with HTML and Attachments:
Email email = EmailBuilder.startingBlank()
    .from("From", "from@example.com")
    .to("1st Receiver", "rec1@example.com")
    .to("2nd Receiver", "rec2@example.com")
    .withSubject("Enhanced Email with HTML and Attachments")
    .withHTMLText("<html><body><h1>Hello!</h1><p>This is an enhanced email with HTML content.</p></body></html>")
    .withAttachment("path/to/attachment.txt") // Replace with the actual file path
    .buildEmail();
Enter fullscreen mode Exit fullscreen mode
  1. Create a Mailer Object using MailerBuilder:
Mailer mailer = MailerBuilder
    .withSMTPServer("smtp.mailtrap.io", 2525, "username", "password")
    .withTransportStrategy(TransportStrategy.SMTPS)
    .buildMailer();
Enter fullscreen mode Exit fullscreen mode
  1. Send the Enhanced Email:
mailer.sendMail(email);
Enter fullscreen mode Exit fullscreen mode

Additional Configuration Options:

Simple Java Mail provides various options to configure both email and the mailer. Developers can tailor the email sending process according to their specific requirements. Detailed information on available configurations can be found in the Simple Java Mail documentation.

Complete Code Example:

// Import statements and package declaration

public class SendEnhancedMail {
    public static void main(String[] args) {
        // Create an Email object with HTML and Attachments using EmailBuilder
        Email email = EmailBuilder.startingBlank()
            .from("From", "from@example.com")
            .to("1st Receiver", "case1@example.com")
            .to("2nd Receiver", "case2@example.com")
            .withSubject("Enhanced Email with HTML and Attachments")
            .withHTMLText("<html><body><h1>Hello!</h1><p>This is an enhanced email with HTML content.</p></body></html>")
            .withAttachment("path/to/attachment.txt") // Replace with the actual file path
            .buildEmail();

        // Create a Mailer object using MailerBuilder
        Mailer mailer = MailerBuilder
            .withSMTPServer("smtp.mailtrap.io", 2525, "username", "password")
            .withTransportStrategy(TransportStrategy.SMTPS)
            .buildMailer();

        // Send the Enhanced Email
        mailer.sendMail(email);
    }
}
Enter fullscreen mode Exit fullscreen mode

Method 3: 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:

Packed with a diverse set of features, SuprSend's comprehensive notification infrastructure management platform empowers users to handle the entire communication flow effortlessly. From integration, routing, template management to creating event automation, SuprSend's single API spans across multiple providers and channels, offering a unified and efficient solution.

Key Benefits Include:

  1. Extensive Integration Options:

  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:

  4. In-App SDK:

  5. Granular Template Management:

  6. Powerful Workspace:

    • Efficiently manage various projects with distinct integrations, workflows, and templates in each workspace.
  7. Unified Analytics:

  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 Transactional emails in JAVA:

Step I: Log in to the SuprSend Account.

  • Visit the SuprSend login page and enter your Email Address and Password.

Get access to try SuprSend

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.
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>

Enter fullscreen mode Exit fullscreen mode

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);
    }

}}

Enter fullscreen mode Exit fullscreen mode

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.

Image description

Learn more about SuprSend Analytics

Explore SuprSend Logs

Closing Remarks:

As businesses grow, managing notification API becomes complex. SuprSend, a notification infrastructure management software, offers a solution by simplifying overall communication stack management.


You may want to check out other SuprSend SDKs too. Consider giving us a star after usage. It's free and open.

GitHub logo suprsend / suprsend-go

SuprSend SDK for go

suprsend-go

SuprSend Go SDK

Installation

go get github.com/suprsend/suprsend-go
Enter fullscreen mode Exit fullscreen mode

Usage

Initialize the SuprSend SDK

import (
    "log"

    suprsend "github.com/suprsend/suprsend-go"
)

func main() {
    opts := []suprsend.ClientOption{
        // suprsend.WithDebug(true),
    }
    suprClient, err := suprsend.NewClient("__api_key__", "__api_secret__", opts...)
    if err != nil {
        log.Println(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

Trigger Workflow

package main
import (
    "log"

    suprsend "github.com/suprsend/suprsend-go"
)

func main() {
    // Instantiate Client
    suprClient, err := suprsend.NewClient("__api_key__", "__api_secret__")
    if err != nil {
        log.Println(err)
        return
    }
    // Create WorkflowTriggerRequest body
    wfReqBody := map[string]interface{}{
        "workflow": "workflow-slug",
        "recipients": []map[string]interface{}{
            {
                "distinct_id": "0f988f74-6982-41c5-8752-facb6911fb08",
                // if $channels is present, communication will be tried on mentioned channels only (for this request).
                // "$channels": []string{"email"},
Enter fullscreen mode Exit fullscreen mode

GitHub logo suprsend / suprsend-py-sdk

SuprSend SDK for python3

suprsend-py-sdk

This package can be included in a python3 project to easily integrate with SuprSend platform.

Installation

suprsend-py-sdk is available on PyPI. You can install using pip.

pip install suprsend-py-sdk
Enter fullscreen mode Exit fullscreen mode

This SDK depends on a system package called libmagic. You can install it as follows:

# On debian based systems
sudo apt install libmagic

# If you are using macOS
brew install libmagic
Enter fullscreen mode Exit fullscreen mode

Usage

Initialize the SuprSend SDK

from suprsend import Suprsend
# Initialize SDK
supr_client = Suprsend("workspace_key", "workspace_secret")
Enter fullscreen mode Exit fullscreen mode

Following example shows a sample request for triggering a workflow. It triggers a pre-created workflow purchase-made to a recipient with id: distinct_id, email: user@example.com & androidpush(fcm-token): __android_push_fcm_token__

from suprsend import WorkflowTriggerRequest
# Prepare Workflow body
wf = WorkflowTriggerRequest(
  body={
    "workflow": "purchase-made"
    "recipients": [
        {
          "distinct_id": "0f988f74-6982-41c5-8752-facb6911fb08",
          # if $channels is present, communication will be tried on mentioned
Enter fullscreen mode Exit fullscreen mode

GitHub logo suprsend / suprsend-node-sdk

Official SuprSend SDK for Node.js

suprsend-node-sdk

This package can be included in a node project to easily integrate with SuprSend platform.

Installation

npm install @suprsend/node-sdk@latest
Enter fullscreen mode Exit fullscreen mode

Initialization

const { Suprsend } = require("@suprsend/node-sdk");

const supr_client = new Suprsend("workspace_key", "workspace_secret");
Enter fullscreen mode Exit fullscreen mode

It is a unified API to trigger workflow and doesn't require user creation before hand. If you are using our frontend SDK's to configure notifications and passing events and user properties from third-party data platforms like Segment, then event-based trigger would be a better choice.

const { Suprsend, WorkflowTriggerRequest } = require("@suprsend/node-sdk");
const supr_client = new Suprsend("workspace_key", "workspace_secret");

// workflow payload
const body = {
  workflow: "_workflow_slug_",
  actor: {
    distinct_id: "0fxxx8f74-xxxx-41c5-8752-xxxcb6911fb08",
    name: "actor_1",
  },
  recipients: [
    {
      distinct_id: "0gxxx9f14-xxxx-23c5-1902-xxxcb6912ab09",
      $email: ["abc@example.com"
Enter fullscreen mode Exit fullscreen mode

GitHub logo suprsend / suprsend-react-inbox

SuprSend SDK for integrating inbox functionality in React applications

@suprsend/react-inbox

Integrating SuprSend Inbox channel in React websites can be done in two ways:

  • SuprSendInbox component which comes with UI and customizing props.
  • SuprSendProvider headless component and hooks, incase you want to totally take control of UI. (example: Full page notifications).

Detailed documentation can be found here: https://docs.suprsend.com/docs/inbox-react

Installation

You can install SuprSend inbox SDK using npm/yarn

npm install @suprsend/react-inbox
Enter fullscreen mode Exit fullscreen mode

SuprSendInbox Integration

After installing, Import the component in your code and use it as given below. Replace the variables with actual values.

import SuprSendInbox from '@suprsend/react-inbox'
import 'react-toastify/dist/ReactToastify.css' // needed for toast notifications, can be ignored if hideToast=true

// add to your react component;
<SuprSendInbox
  workspaceKey='<workspace_key>'
  subscriberId='<subscriber_id>'
  distinctId='<distinct_id>'
/>
Enter fullscreen mode Exit fullscreen mode
interface ISuprSendInbox {
  workspaceKey: string
  distinctId: string | null
  subscriberId: string | null
  tenantId?: string
  stores?: IStore[]
  pageSize?: number
  pagination?: boolean
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
theelitegentleman profile image
Buhake Sindi

Hi Nik,

For your first example, it's very misleading. Any Jakarta EE certified application server can handle JavaMail Session and its resource from the application server itself. All the developer has to do is to @Inject the Session itself. You can set up the mail session at application server level if you're worried about the "cons" of using JavaMail.

The example you provided is running it locally. In enterprises, no companies does that. The beauty of what I just said is that the JavaMail is an Enterprise Java specification that all JakartaEE certified servers can implement, including SpringBoot, and no need for 3rd party dependencies in your code.