How to Send Email Notifications using JAVA? (3 Methods With Code Examples)
Tags: java, javascript, programming, opensource
Published: 2024-01-13 13:53:50

Some of our articles:

1. [Building a Scalable Notification System with gRPC and Microservices](https://dev.to/suprsend/building-a-scalable-notification-service-with-grpc-and-microservices-l6d)
2. [How to Send Email Notifications using Python? (With Code Examples)](https://dev.to/nikl/how-to-send-email-notifications-using-python-with-code-examples-3286)
3. [A Complete Guide on Notification Infrastructure for Modern Applications in 2023](https://dev.to/suprsend/a-complete-guide-on-notification-infrastructure-for-modern-applications-in-2023-13b9)

---

## Method 1: Using JavaMail API

### Overview:

JavaMail API, a platform-independent and protocol-independent framework, [empowers Java client applications](https://www.suprsend.com/post/how-to-send-transactional-emails-with-java-3-methods-with-codes---javamail-api-simple-java-mail-suprsend) 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](https://www.suprsend.com/post/how-to-send-transactional-emails-in-a-spring-boot-application-using-java-javamailsender-with-codes).

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

```java
Properties properties = new Properties(); // properties object contains host information
Session session = Session.getDefaultInstance(properties, null);
```

   - Alternatively:

```java
Properties properties = new Properties(); // properties object contains host information 
Session session = Session.getInstance(properties, null);
```

   - Authentication for a network connection:

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

#### Step 3: Composing the Email

   - Utilize `javax.mail.internet.MimeMessage` subclass to configure sender, receiver, subject, and message body.

```java
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");
```

#### Step 4: Adding Attachments

   - For including attachments, create a `Multipart` object and add a `BodyPart` for each attachment.

```java
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);
```

#### Step 5: Sending the Email

   - Employ the `javax.mail.Transport` class to send the email.

```java
Transport.send(message);
```

### Complete Code Example:

```java
// 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();
      }
   }
}
```

---


## 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:

2. **Create an Email Object with HTML and Attachments:**

```java
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();
```

3. **Create a Mailer Object using MailerBuilder:**

```java
Mailer mailer = MailerBuilder
    .withSMTPServer("smtp.mailtrap.io", 2525, "username", "password")
    .withTransportStrategy(TransportStrategy.SMTPS)
    .buildMailer();
```

4. **Send the Enhanced Email:**

```java
mailer.sendMail(email);
```

#### 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:

```java
// 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);
    }
}
```

---

## 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:**
   - Seamless [integration with 50+ Communication Service Providers](https://www.suprsend.com/integration-with-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](https://docs.suprsend.com/docs/java-sdk) once, and your product team will manage everything else.

3. **Intelligent Routing:**
   - Create and [implement intelligent cross-channel flows](https://www.suprsend.com/products/smart-routing) across providers without technical dependencies.

4. **In-App SDK:**
   - Provides a fully loaded, [developer-ready in-app layer](https://docs.suprsend.com/docs/inbox-overview) for both web and mobile applications.

5. **Granular Template Management:**
   - Utilize an intuitive [drag & drop editor for designing templates](https://www.suprsend.com/products/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](https://www.suprsend.com/products/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 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](https://app.suprsend.com/en/signup/) 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4cow0ppuznw733gyo0uy.png)


**Step II: Integrate with Email(s).**
   - SuprSend provides a [ready-to-integrate provider list](https://www.suprsend.com/integration-with-providers) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qv5lsyfa0bpo5b9a7bvp.png)



**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zoir8uieivl5cgwgkeee.png)



**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f8paxfwzenhmgbif7kr3.png)


**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](https://docs.suprsend.com/docs/integrate-java-sdk ).


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

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3w3v7npa8bbdufkt0mj3.png)


[Learn more about SuprSend Analytics](#) 

[Explore SuprSend Logs](https://docs.suprsend.com/docs/logging)

### 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 suprsend/suprsend-go %}

---

{% github suprsend/suprsend-py-sdk %}

---
{% github suprsend/suprsend-node-sdk %}

---
{% github suprsend/suprsend-react-inbox %}