Send emails using Java (Javamail API or Simple Java Mail or SuprSend Java SDK)
Nik L.
Posted on August 2, 2024
Method 1: Using JavaMail API for Email Notifications
Overview:
The JavaMail API is a robust, platform-independent, and protocol-independent framework designed to support Java client applications in performing comprehensive email and messaging functionalities. This API offers a generic interface with abstract classes representing various objects created in transactional email systems. It is especially useful for enterprise-level applications where reliability and extensive functionalities are paramount.
Pros:
Well-Structured and Widely Adopted:
JavaMail API is renowned for its solid structure and widespread usage, particularly in enterprise environments.
Versatile Functionality:
It provides an extensive set of functionalities, including reading, composing, and sending emails.
Programmatic Integration:
Simplifies the integration with other programs, making it easier to send confirmations and other messages programmatically.
Cons:
Extended Compilation Time:
Developers may face longer code compilation times due to the API's complexity.
Memory Consumption:
Using the JavaMail API can lead to significant consumption of Java heap space.
Implementation Steps:
Step 1: Installing JavaMail API
Include JAR files (mail.jar and activation.jar) in the CLASSPATH.
Configure an SMTP server (e.g., Pepipost) for email transmission.
Step 2: Setting Up the Mail Session
Create a session object with host information using javax.mail.Session.
Use the javax.mail.internet.MimeMessage subclass to set the sender, receiver, subject, and message body.
MimeMessagemessage=newMimeMessage(session);message.setFrom(newInternetAddress(from));message.addRecipient(Message.RecipientType.TO,newInternetAddress(to));message.setSubject("This is the email subject");message.setText("This is the email body");
Step 4: Adding Attachments
To include attachments, create a Multipart object and add a BodyPart for each attachment.
Multipartmultipart=newMimeMultipart();BodyPartmessageBodyPart=newMimeBodyPart();messageBodyPart.setText("This is the email body");multipart.addBodyPart(messageBodyPart);messageBodyPart=newMimeBodyPart();DataSourcesource=newFileDataSource("path/to/attachment.txt");messageBodyPart.setDataHandler(newDataHandler(source));messageBodyPart.setFileName("attachment.txt");multipart.addBodyPart(messageBodyPart);message.setContent(multipart);
Step 5: Sending the Email
Use the javax.mail.Transport class to send the email.
Transport.send(message);
Complete Code Example:
importjava.util.Properties;importjavax.mail.*;importjavax.mail.internet.*;importjavax.activation.*;publicclassSendMail{publicstaticvoidmain(String[]args){Stringto="receiver@gmail.com";Stringfrom="sender@gmail.com";Stringhost="smtp.gmail.com";Propertiesproperties=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");Sessionsession=Session.getInstance(properties,newjavax.mail.Authenticator(){protectedPasswordAuthenticationgetPasswordAuthentication(){returnnewPasswordAuthentication("sender@gmail.com","password");}});try{MimeMessagemessage=newMimeMessage(session);message.setFrom(newInternetAddress(from));message.addRecipient(Message.RecipientType.TO,newInternetAddress(to));message.setSubject("Your email subject goes here");Multipartmultipart=newMimeMultipart();BodyPartmessageBodyPart=newMimeBodyPart();messageBodyPart.setText("You have a new message");multipart.addBodyPart(messageBodyPart);messageBodyPart=newMimeBodyPart();DataSourcesource=newFileDataSource("path/to/attachment.txt");messageBodyPart.setDataHandler(newDataHandler(source));messageBodyPart.setFileName("attachment.txt");multipart.addBodyPart(messageBodyPart);message.setContent(multipart);Transport.send(message);}catch(MessagingExceptionmex){mex.printStackTrace();}}}
Method 2: Using Simple Java Mail for Email Notifications
Overview:
Simple Java Mail is a user-friendly mailing library designed to simplify the process of sending SMTP emails in Java. It serves as a wrapper around the JavaMail API, streamlining the email sending process by reducing the complexity of the underlying API.
Pros:
Robust and Lightweight:
Simple Java Mail is robust while maintaining a lightweight footprint of 134kB.
RFC Compliance:
It complies with all relevant RFCs, ensuring compatibility with various email clients.
Authenticated SOCKS Proxy Support:
Supports sending emails through an authenticated SOCKS proxy.
Advanced Features:
Offers support for HTML content, images, and attachments, and allows sending emails to multiple recipients simultaneously.
Cons:
Limited Community Support:
The community support for Simple Java Mail is smaller compared to JavaMail API.
Implementation Steps:
Step 1: Creating an Email Object with HTML and Attachments
Emailemail=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").buildEmail();
Step 2: Creating a Mailer Object using MailerBuilder
importorg.simplejavamail.api.email.Email;importorg.simplejavamail.email.EmailBuilder;importorg.simplejavamail.mailer.Mailer;importorg.simplejavamail.mailer.MailerBuilder;importorg.simplejavamail.api.mailer.config.TransportStrategy;publicclassSendEnhancedMail{publicstaticvoidmain(String[]args){Emailemail=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").buildEmail();Mailermailer=MailerBuilder.withSMTPServer("smtp.mailtrap.io",2525,"username","password").withTransportStrategy(TransportStrategy.SMTPS).buildMailer();mailer.sendMail(email);}}
Method 3: Using SuprSend for Multichannel Notifications with JAVA SDKs
Overview:
SuprSend offers a comprehensive third-party multichannel notification infrastructure that supports sending notifications across various channels like email, SMS, and push notifications through a unified API. By leveraging SuprSend, developers can manage complex notification workflows seamlessly.
Key Features & Benefits:
Extensive Integration Options:
Integrates seamlessly with over 50 Communication Service Providers (CSPs) and supports multiple channels including Mixpanel, Segment, Twilio, Mailchimp, Slack, Teams, SNS, Vonage, Whatsapp, and more.
No Tech Dependency:
Manages the entire notification lifecycle without heavy reliance on the engineering team. Integrate the JAVA SDK once, and the product team can handle the rest.
Intelligent Routing:
Implements intelligent cross-channel flows across providers without requiring technical dependencies.
In-App SDK:
Provides a developer-ready in-app layer for both web and mobile applications.
Granular Template Management:
Features an intuitive drag & drop editor for designing templates, offering superior control over content.
Powerful Workspace:
Manages multiple projects with distinct integrations, workflows, and templates within each workspace.
Unified Analytics:
Provides a unified view of cross-channel analytics, enabling data-driven decision-making.
Smart Automation:
Automates synchronization, refreshing, and notification triggers to streamline operations.
Scalability:
Automates scalability, ensuring a hassle-free experience.
Cons:
Cost Considerations:
Managing multiple notification channels may incur costs.
*Monthly Notification Limit:*
Though SuprSend provides 10k notifications free every month, which resets every month, you can also buy credits.
Limits:**
There may be restrictions on the number of notifications per month.
Implementation Steps:
Step 1: Integrating the JAVA SDK
Install the SuprSend JAVA SDK:
Add the SDK to your JAVA project via Maven or Gradle.
Step 2: Configuring the API Key and Workspace Secret
Set Up Configuration:
Obtain the API key and workspace secret from your SuprSend account and configure them in your JAVA project.
Step 3: Creating and Sending Notifications
Send Notifications via JAVA SDK:
Use the SDK to send notifications, specifying the required channel (email, SMS, push, etc.) and the content.
importcom.suprsend.Notification;importcom.suprsend.NotificationBuilder;importcom.suprsend.SuprSendClient;publicclassSendNotification{publicstaticvoidmain(String[]args){// Initialize the SuprSendClient with API key and Workspace SecretSuprSendClientclient=newSuprSendClient("your_api_key","your_workspace_secret");// Build the notificationNotificationnotification=NotificationBuilder.startingBlank().withRecipientEmail("recipient@example.com").withRecipientSMS("recipient_phone_number").withSubject("Notification Subject").withHTMLBody("<html><body><h1>Hello!</h1><p>This is a multichannel notification.</p></body></html>").build();// Send the notificationclient.sendNotification(notification);}}
Complete Code Example with JAVA SDK:
importcom.suprsend.Notification;importcom.suprsend.NotificationBuilder;importcom.suprsend.SuprSendClient;publicclassSuprSendExample{publicstaticvoidmain(String[]args){// Initialize the SuprSendClient with API key and Workspace SecretSuprSendClientclient=newSuprSendClient("your_api_key","your_workspace_secret");// Create the notificationNotificationnotification=NotificationBuilder.startingBlank().withRecipientEmail("receiver@example.com").withSubject("Subject of the Notification").withHTMLBody("<html><body><h1>Hello!</h1><p>This is a notification from SuprSend.</p></body></html>").withAttachment("path/to/attachment.txt").build();// Send the notificationclient.sendNotification(notification);}}
These methods offer a comprehensive guide to sending email notifications using Java, with varying levels of complexity and integration capabilities to suit different needs and scenarios.
You may want to check out other SuprSend SDKs too. Consider giving us a star after usage. It's free and open.
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__
fromsuprsendimportWorkflowTriggerRequest# Prepare Workflow bodywf=WorkflowTriggerRequest(
body={
"workflow": "purchase-made""recipients": [
{
"distinct_id": "0f988f74-6982-41c5-8752-facb6911fb08",
# if $channels is present, communication will be tried on mentioned
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.
After installing, Import the component in your code and use it as given below. Replace the variables with actual values.
importSuprSendInboxfrom'@suprsend/react-inbox'import'react-toastify/dist/ReactToastify.css'// needed for toast notifications, can be ignored if hideToast=true// add to your react component;<SuprSendInboxworkspaceKey='<workspace_key>'subscriberId='<subscriber_id>'distinctId='<distinct_id>'/>