Utilize javax.mail.internet.MimeMessage subclass to configure sender, receiver, subject, and message body.
MimeMessagemessage=newMimeMessage(session);// Sender emailmessage.setFrom(newInternetAddress(from));// Receiver emailmessage.addRecipient(Message.RecipientType.TO,newInternetAddress(to));// Email subjectmessage.setSubject("This is the email subject");// Email bodymessage.setText("This is the email body");
Step 4: Adding Attachments
For including attachments, create a Multipart object and add a BodyPart for each attachment.
Multipartmultipart=newMimeMultipart();// Create a BodyPart for the main email contentBodyPartmessageBodyPart=newMimeBodyPart();messageBodyPart.setText("This is the email body");// Add the main content BodyPart to the Multipartmultipart.addBodyPart(messageBodyPart);// Create a BodyPart for the attachmentmessageBodyPart=newMimeBodyPart();DataSourcesource=newFileDataSource("path/to/attachment.txt");// Replace with the actual file pathmessageBodyPart.setDataHandler(newDataHandler(source));messageBodyPart.setFileName("attachment.txt");// Add the attachment BodyPart to the Multipartmultipart.addBodyPart(messageBodyPart);// Set the Multipart as the message contentmessage.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 declarationpublicclassSendMail{publicstaticvoidmain(String[]args){// Email detailsStringto="receiver@gmail.com";Stringfrom="sender@gmail.com";Stringhost="smtp.gmail.com";// System properties and configurationPropertiesproperties=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 authenticationSessionsession=Session.getInstance(properties,newjavax.mail.Authenticator(){protectedPasswordAuthenticationgetPasswordAuthentication(){returnnewPasswordAuthentication("sender@gmail.com","password");}});try{// Creating and configuring the MimeMessageMimeMessagemessage=newMimeMessage(session);message.setFrom(newInternetAddress(from));message.addRecipient(Message.RecipientType.TO,newInternetAddress(to));message.setSubject("Your email subject goes here");// Adding AttachmentsMultipartmultipart=newMimeMultipart();BodyPartmessageBodyPart=newMimeBodyPart();messageBodyPart.setText("You have a new message");multipart.addBodyPart(messageBodyPart);messageBodyPart=newMimeBodyPart();DataSourcesource=newFileDataSource("path/to/attachment.txt");// Replace with the actual file pathmessageBodyPart.setDataHandler(newDataHandler(source));messageBodyPart.setFileName("attachment.txt");multipart.addBodyPart(messageBodyPart);message.setContent(multipart);// Sending the emailTransport.send(message);}catch(MessagingExceptionmex){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:
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")// Replace with the actual file path.buildEmail();
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 declarationpublicclassSendEnhancedMail{publicstaticvoidmain(String[]args){// Create an Email object with HTML and Attachments using EmailBuilderEmailemail=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 MailerBuilderMailermailer=MailerBuilder.withSMTPServer("smtp.mailtrap.io",2525,"username","password").withTransportStrategy(TransportStrategy.SMTPS).buildMailer();// Send the Enhanced Emailmailer.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.
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.
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.
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.
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.
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.
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>'/>