JavaMail

Send emails in Java

&NewLine;<p class&equals;"wp-block-paragraph">Today we will discuss how to send <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;java-mail-api-tutorial&sol;"><strong>emails from your Java app&period;<&sol;strong><&sol;a> In general&comma; you have two main options&colon; either use the native built-in functionality or try some external packages&period; Java provides a quite comprehensive email package&period; Let’s start with learning how to use it and then have a quick look at other available options &lpar;there are not that many of them&comma; indeed&rpar;&period;  <&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<h2 class&equals;"wp-block-heading">What is JavaMail <&sol;h2>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">JavaMail is an official Java API for sending and receiving emails&period; Starting from July 2019&comma; JavaMail is known as Jakarta Mail&period; Oracle transferred the rights for Java EE to the Eclipse Foundation&comma; and now the software evolves under the Jakarta EE brand&period; The official documentation for Jakarta Mail API can be now found <a href&equals;"https&colon;&sol;&sol;eclipse-ee4j&period;github&period;io&sol;mail&sol;docs&sol;api&sol;">here<&sol;a>&period; <&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph"> In fact&comma; only the project name changed with the Jakarta Mail release&period; Let’s see how to install it first&period; The mail package is already included in Jakarta EE and the Java EE platforms&period; <&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph"> To download the latest version&comma; go to the Jakarta Mail Implementation page on <a href&equals;"https&colon;&sol;&sol;eclipse-ee4j&period;github&period;io&sol;mail&sol;&num;Download&lowbar;Jakarta&lowbar;Mail&lowbar;Release">GitHub<&sol;a>&period; You will need <em>jakarta&period;mail&period;jar file&colon; <&sol;em>insert it in your CLASSPATH environment then&period; Alternatively&comma; you can add it with Maven dependencies as follows&colon;  <&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<pre class&equals;"wp-block-code"><code> &lt&semi;dependencies>&NewLine; &lt&semi;dependency>&NewLine; &lt&semi;groupId>com&period;sun&period;mail&lt&semi;&sol;groupId>&NewLine; &lt&semi;artifactId>jakarta&period;mail&lt&semi;&sol;artifactId>&NewLine; &lt&semi;version>1&period;6&period;4&lt&semi;&sol;version>&NewLine; &lt&semi;&sol;dependency>&NewLine; &lt&semi;&sol;dependencies>&NewLine;<&sol;code><&sol;pre>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph"> The mail system in Java is built with classes provided by Jakarta Mail API&period; You will find the detailed descriptions in the official documentation&comma; while in this tutorial we will refer to the main points&comma; which allow us to&colon;<&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<ul class&equals;"wp-block-list"><li>add email headers<&sol;li><li>create plain text and HTML messages<&sol;li><li>embed images<&sol;li><li>attach files<&sol;li><li>send messages via SMTP using password authentication <&sol;li><&sol;ul>&NewLine;&NewLine;&NewLine;&NewLine;<h2 class&equals;"wp-block-heading"> How to build a simple email  <&sol;h2>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">&NewLine;To create a simple mail&comma; we need to import the necessary classes&colon;<&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<ul class&equals;"wp-block-list"><li><strong>javax&period;mail&period;Message<&sol;strong> &&num;8211&semi; an abstract class&comma; creates a message&nbsp&semi;<ul><li><strong>javax&period;mail&period;internet&period;MimeMessage <&sol;strong>&&num;8211&semi; its sub-class<&sol;li><&sol;ul><&sol;li><li><strong>javax&period;mail&period;MessagingException <&sol;strong>&&num;8211&semi; notifies about possible errors<&sol;li><li><strong>javax&period;mail&period;PasswordAuthentication<&sol;strong> &&num;8211&semi; requires password authentication for an SMTP server<&sol;li><li><strong>javax&period;mail&period;Session <&sol;strong>&&num;8211&semi; joins all the properties<&sol;li><li><strong>javax&period;mail&period;Transport &&num;8211&semi; <&sol;strong>sends message<&sol;li><li><strong>javax&period;mail&period;internet&period;InternetAddress<&sol;strong> &&num;8211&semi; to add email addresses<&sol;li><&sol;ul>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">Then we need to specify the sending server in properties and set message parameters as follows&colon;<&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<pre class&equals;"wp-block-code"><code>package com&period;example&period;smtp&semi;&NewLine;import java&period;util&period;Properties&semi;&NewLine;&NewLine;import javax&period;mail&period;Message&semi;&NewLine;import javax&period;mail&period;MessagingException&semi;&NewLine;import javax&period;mail&period;PasswordAuthentication&semi;&NewLine;import javax&period;mail&period;Session&semi;&NewLine;import javax&period;mail&period;Transport&semi;&NewLine;import javax&period;mail&period;internet&period;InternetAddress&semi;&NewLine;import javax&period;mail&period;internet&period;MimeMessage&semi;&NewLine;&NewLine;public class SendEmail &lbrace;&NewLine; public static void main&lpar;String&&num;91&semi;&rsqb; args&rpar; &lbrace;&NewLine; &sol;&sol; Put recipient’s address&NewLine; String to &equals; "test&commat;example&period;com"&semi;&NewLine;&NewLine; &sol;&sol; Put sender’s address&NewLine; String from &equals; "from&commat;example&period;com"&semi;&NewLine; final String username &equals; "username&commat;example&period;com"&semi;&NewLine; final String password &equals; "yourpassword"&semi;&NewLine;&NewLine; &sol;&sol; Paste host address &NewLine; String host &equals; "smtp&period;example&period;com"&semi;&NewLine;&NewLine; Properties props &equals; new Properties&lpar;&rpar;&semi;&NewLine; props&period;put&lpar;"mail&period;smtp&period;auth"&comma; "true"&rpar;&semi;&NewLine; props&period;put&lpar;"mail&period;smtp&period;starttls&period;enable"&comma; "true"&rpar;&semi; &NewLine; props&period;put&lpar;"mail&period;smtp&period;host"&comma; host&rpar;&semi;&NewLine; props&period;put&lpar;"mail&period;smtp&period;port"&comma; "2525"&rpar;&semi;&sol;&sol; use the port appropriate for your host &NewLine;&NewLine; &sol;&sol; Get the Session object&period;&NewLine; Session session &equals; Session&period;getInstance&lpar;props&comma;&NewLine; new javax&period;mail&period;Authenticator&lpar;&rpar; &lbrace;&NewLine; protected PasswordAuthentication getPasswordAuthentication&lpar;&rpar; &lbrace;&NewLine; return new PasswordAuthentication&lpar;username&comma; password&rpar;&semi;&NewLine; &rcub;&NewLine; &rcub;&rpar;&semi;&NewLine;&NewLine; try &lbrace;&NewLine; &sol;&sol; Create a default MimeMessage object&period;&NewLine; Message message &equals; new MimeMessage&lpar;session&rpar;&semi;&NewLine; &NewLine; &sol;&sol; Set From&colon; header field &NewLine; message&period;setFrom&lpar;new InternetAddress&lpar;from&rpar;&rpar;&semi;&NewLine; &NewLine; &sol;&sol; Set To&colon; header field&NewLine; message&period;setRecipients&lpar;Message&period;RecipientType&period;TO&comma;&NewLine; InternetAddress&period;parse&lpar;to&rpar;&rpar;&semi;&NewLine; &NewLine; &sol;&sol; Set Subject&colon; header field&NewLine; message&period;setSubject&lpar;"How to send a simple email in Java"&rpar;&semi;&NewLine; &NewLine; &sol;&sol; Put the content of your message&NewLine; message&period;setText&lpar;"Hi there&comma; this is my first message sent in Java"&rpar;&semi;&NewLine;&NewLine; &sol;&sol; Send message&NewLine; Transport&period;send&lpar;message&rpar;&semi;&NewLine;&NewLine; System&period;out&period;println&lpar;"Sent message successfully&period;&period;&period;&period;"&rpar;&semi;&NewLine;&NewLine; &rcub; catch &lpar;MessagingException e&rpar; &lbrace;&NewLine; throw new RuntimeException&lpar;e&rpar;&semi;&NewLine; &rcub;&NewLine; &rcub;&NewLine;&rcub;&NewLine;<&sol;code><&sol;pre>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph"> Here is how this message should look in your test email inbox&colon; <&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<figure class&equals;"wp-block-image"><img src&equals;"https&colon;&sol;&sol;lh6&period;googleusercontent&period;com&sol;aufp&lowbar;sbTnMvhJFlISNiLGC4BaVmCVejKLWQYbuWxegf4Z5rPfFCDIsBJwQYFDEN2c4I4H&lowbar;&lowbar;PHEnyEl6ahlwUwwLRt9yT&lowbar;nD7Fl&lowbar;8ctOTZwXrPY5uEYJ5CXiOsKVCU4&lowbar;q77SgW6Cg" alt&equals;"Send emails in Java"&sol;><figcaption><strong>Send emails in Java<&sol;strong><&sol;figcaption><&sol;figure>&NewLine;&NewLine;&NewLine;&NewLine;<h2 class&equals;"wp-block-heading"> Let’s add HTML content<&sol;h2>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">To build a simple template with text formatting&comma; links&comma; or images&comma; we will use HTML&period; For this purpose&comma; we will use <strong>SendHTMLEmail<&sol;strong> class &lpar;unlike SendEmail for a simple message in our previous example&rpar; and set <strong>MimeMessage&period;setContent<&sol;strong>&lpar;Object&comma; String&rpar;<strong>&colon;<&sol;strong><&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<pre class&equals;"wp-block-code"><code>package com&period;example&period;smtp&semi;&NewLine;import java&period;util&period;Properties&semi;&NewLine;&NewLine;import javax&period;mail&period;Message&semi;&NewLine;import javax&period;mail&period;MessagingException&semi;&NewLine;import javax&period;mail&period;PasswordAuthentication&semi;&NewLine;import javax&period;mail&period;Session&semi;&NewLine;import javax&period;mail&period;Transport&semi;&NewLine;import javax&period;mail&period;internet&period;InternetAddress&semi;&NewLine;import javax&period;mail&period;internet&period;MimeMessage&semi;&NewLine;&NewLine;public class SendHTMLEmail &lbrace;&NewLine; public static void main&lpar;String&&num;91&semi; &rsqb; args&rpar; &lbrace;&NewLine; String to &equals; "johndoe&commat;example&period;com"&semi;&NewLine;&NewLine; String from &equals; "yourmail&commat;example&period;com"&semi;&NewLine; final String username &equals; "yourusername"&semi;&NewLine; final String password &equals; "yourpassword"&NewLine;&NewLine; String host &equals; "smtp&period;example&period;com"&semi;&NewLine;&NewLine; Properties props &equals; new Properties&lpar;&rpar;&semi;&NewLine; props&period;put&lpar;"mail&period;smtp&period;auth"&comma; "true"&rpar;&semi;&NewLine; props&period;put&lpar;"mail&period;smtp&period;starttls&period;enable"&comma; "true"&rpar;&semi;&NewLine; props&period;put&lpar;"mail&period;smtp&period;host"&comma; host&rpar;&semi;&NewLine; props&period;put&lpar;"mail&period;smtp&period;port"&comma; "2525"&rpar;&semi;&NewLine;&NewLine; &sol;&sol; Get the Session object&period;&NewLine; Session session &equals; Session&period;getInstance&lpar;props&comma;&NewLine; new javax&period;mail&period;Authenticator&lpar;&rpar; &lbrace;&NewLine; protected PasswordAuthentication getPasswordAuthentication&lpar;&rpar; &lbrace;&NewLine; return new PasswordAuthentication&lpar;username&comma; password&rpar;&semi;&NewLine; &rcub;&NewLine; &rcub;&rpar;&semi;&NewLine;&NewLine; try &lbrace;&NewLine; &sol;&sol; Create a default MimeMessage object&period;&NewLine; Message message &equals; new MimeMessage&lpar;session&rpar;&semi;&NewLine;&NewLine; message&period;setFrom&lpar;new InternetAddress&lpar;from&rpar;&rpar;&semi;&NewLine;&NewLine; message&period;setRecipients&lpar;Message&period;RecipientType&period;TO&comma;&NewLine; InternetAddress&period;parse&lpar;to&rpar;&rpar;&semi;&NewLine;&NewLine; message&period;setSubject&lpar;"newHTML message"&rpar;&semi;&NewLine;&NewLine; message&period;setContent&lpar;&NewLine; "&lt&semi;h1>This is header&lt&semi;&sol;h1>"&NewLine;&comma;&NewLine; "text&sol;html"&rpar;&semi;&NewLine;&NewLine; &sol;&sol; Send message&NewLine; Transport&period;send&lpar;message&rpar;&semi;&NewLine;&NewLine; System&period;out&period;println&lpar;"Sent message successfully&period;&period;&period;&period;"&rpar;&semi;&NewLine;&NewLine; &rcub; catch &lpar;MessagingException e&rpar; &lbrace;&NewLine; e&period;printStackTrace&lpar;&rpar;&semi;&NewLine; throw new RuntimeException&lpar;e&rpar;&semi;&NewLine; &rcub;&NewLine; &rcub;&NewLine;&rcub;&NewLine;<&sol;code><&sol;pre>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph"> Here is how the result should look in your test email service&colon; <&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<figure class&equals;"wp-block-image"><img src&equals;"https&colon;&sol;&sol;lh4&period;googleusercontent&period;com&sol;ANwzhfCjXhhGCymMBYeD6EwfcTKvyj8HFN0Eq08s-sfIEq72u2j&lowbar;JsTSG8oDTzCHULzaqQc0Jpjy1arBG95FnO&lowbar;mi9W2A6sT&lowbar;HicWgpuboiuizmT-N0G554RXnB&lowbar;sdturY2e2tAQ" alt&equals;"Send emails in Java with HTML"&sol;><figcaption><strong>Send emails in Java with HTML<&sol;strong><&sol;figcaption><&sol;figure>&NewLine;&NewLine;&NewLine;&NewLine;<h2 class&equals;"wp-block-heading">How to attach files<&sol;h2>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">You can attach files with the attach file method specified in the MimeBodyPart as follows&colon; <&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<pre class&equals;"wp-block-code"><code>public void attachFile&lpar;File file&comma; Multipart multipart&comma; MimeBodyPart messageBodyPart&rpar;&NewLine;&NewLine; &lbrace; DataSource source &equals; new FileDataSource&lpar;file&rpar;&semi;&NewLine;&NewLine;messageBodyPart&period;setDataHandler&lpar;new DataHandler&lpar;source&rpar;&rpar;&semi;&NewLine;messageBodyPart&period;setFileName&lpar;file&period;getName&lpar;&rpar;&rpar;&semi;&NewLine;&NewLine;multipart&period;addBodyPart&lpar;messageBodyPart&rpar;&semi; &rcub;&NewLine;<&sol;code><&sol;pre>&NewLine;&NewLine;&NewLine;&NewLine;<h2 class&equals;"wp-block-heading">Other ways to send emails in Java <&sol;h2>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">Above&comma; we have gone through the main capabilities of the native Java email functionality&period; What other options can you consider&quest;<&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">&NewLine;The most popular alternatives are&colon;<&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<ul class&equals;"wp-block-list"><li>the Spring Framework&&num;8217&semi;s email library&nbsp&semi;<&sol;li><li>Apache Common Emails<&sol;li><li>Simple Java Mail library<&sol;li><&sol;ul>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph">It is worth mentioning that all of them are built on top of the JavaMail API&period;&nbsp&semi;<&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph"> This article on sending emails in Java was originally published on the <a href&equals;"https&colon;&sol;&sol;blog&period;mailtrap&period;io&sol;sending-email-using-java&sol;" target&equals;"&lowbar;blank" rel&equals;"noreferrer noopener" aria-label&equals;"ava was originally published on the Mailtrap blog&period; &lpar;opens in a new tab&rpar;">Mailtrap blog&period; <&sol;a><&sol;p>&NewLine;&NewLine;&NewLine;&NewLine;<p class&equals;"wp-block-paragraph"> <&sol;p>&NewLine;<div class&equals;"wp-post-navigation"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <div class&equals;"wp-post-navigation-pre"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;authentication-using-javamail-smtp&sol;">Previous<&sol;a> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <&sol;div> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <div class&equals;"wp-post-navigation-next"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <&sol;div> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;<&sol;div>&NewLine;<script type&equals;"text&sol;javascript">&NewLine;jQuery&lpar;document&rpar;&period;ready&lpar;function&lpar;&dollar;&rpar; &lbrace;&NewLine; &dollar;&period;post&lpar;'https&colon;&sol;&sol;dineshonjava&period;com&sol;wp-admin&sol;admin-ajax&period;php'&comma; &lbrace;action&colon; 'mts&lowbar;view&lowbar;count'&comma; id&colon; '4500'&rcub;&rpar;&semi;&NewLine;&rcub;&rpar;&semi;&NewLine;<&sol;script>

Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

4 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

4 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

4 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

4 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

4 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

4 years ago