Some of our articles:
- Building a Scalable Notification System with gRPC and Microservices
- How to Send Email Notifications using Python? (With Code Examples)
- 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:
Well-structured and Widely Used:
- JavaMail API is known for its robust structure and widespread adoption, particularly in enterprise applications.
Versatility in Functionality:
- Offers a comprehensive set of functionalities, including reading, composing, and sending emails.
Programmatic Accessibility:
- Facilitates integration with other programs, simplifying the process of sending mail confirmations or other messages.
Cons:
Extended Compilation Time:
- Developers might experience longer code compilation times due to the nature of JavaMail API.
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
andactivation.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);
- Alternatively:
Properties properties = new Properties(); // properties object contains host information
Session session = Session.getInstance(properties, null);
- Authentication for a network connection:
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.
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 aBodyPart
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);
Step 5: Sending the Email
- Employ the
javax.mail.Transport
class to send the email.
Transport.send(message);
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();
}
}
}
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:
Robust, Small, and Lightweight:
- Simple Java Mail boasts robustness while maintaining a small and lightweight footprint (134kB).
Strict RFC Compliance:
- Complies with all RFCs, ensuring compatibility with various email clients.
Authenticated SOCKS Proxy Support:
- Unique capability to send emails through an authenticated SOCKS proxy.
Advanced Features:
- Provides support for HTML, images, and attachments.
- Allows sending emails to multiple receivers simultaneously.
Cons:
- 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:
- 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();
- 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);
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);
}
}
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:
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.
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.
Intelligent Routing:
- Create and implement intelligent cross-channel flows across providers without technical dependencies.
In-App SDK:
- Provides a fully loaded, developer-ready in-app layer for both web and mobile applications.
Granular Template Management:
- Utilize an intuitive drag & drop editor for designing templates, offering superior control over the content.
Powerful Workspace:
- Efficiently manage various projects with distinct integrations, workflows, and templates in each workspace.
Unified Analytics:
- Track, measure, and make data-driven decisions with a unified view of cross-channel analytics across vendors.
Smart Automation:
- Automate synchronization, refreshing, and notification triggers, allowing more focus on critical tasks.
Quick Scalability:
- SuprSend automates scalability, putting it on autopilot for a hassle-free experience.
Cons:
Cost Considerations:
- Managing multiple notification channels may incur costs. Monthly Notification Limits:
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.
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.
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.
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.
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>
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.
Learn more about SuprSend Analytics
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.
%[INVALID_URL]{% github suprsend/suprsend-py-sdk %}
%[INVALID_URL]
{% github suprsend/suprsend-react-inbox %}