<p class="wp-block-paragraph">Today we will discuss how to send <a href="https://dineshonjava.com/java-mail-api-tutorial/"><strong>emails from your Java app.</strong></a> In general, you have two main options: either use the native built-in functionality or try some external packages. Java provides a quite comprehensive email package. Let’s start with learning how to use it and then have a quick look at other available options (there are not that many of them, indeed). </p>



<h2 class="wp-block-heading">What is JavaMail </h2>



<p class="wp-block-paragraph">JavaMail is an official Java API for sending and receiving emails. Starting from July 2019, JavaMail is known as Jakarta Mail. Oracle transferred the rights for Java EE to the Eclipse Foundation, and now the software evolves under the Jakarta EE brand. The official documentation for Jakarta Mail API can be now found <a href="https://eclipse-ee4j.github.io/mail/docs/api/">here</a>. </p>



<p class="wp-block-paragraph"> In fact, only the project name changed with the Jakarta Mail release. Let’s see how to install it first. The mail package is already included in Jakarta EE and the Java EE platforms. </p>



<p class="wp-block-paragraph"> To download the latest version, go to the Jakarta Mail Implementation page on <a href="https://eclipse-ee4j.github.io/mail/#Download_Jakarta_Mail_Release">GitHub</a>. You will need <em>jakarta.mail.jar file: </em>insert it in your CLASSPATH environment then. Alternatively, you can add it with Maven dependencies as follows: </p>



<pre class="wp-block-code"><code> <;dependencies>
 <;dependency>
 <;groupId>com.sun.mail<;/groupId>
 <;artifactId>jakarta.mail<;/artifactId>
 <;version>1.6.4<;/version>
 <;/dependency>
 <;/dependencies>
</code></pre>



<p class="wp-block-paragraph"> The mail system in Java is built with classes provided by Jakarta Mail API. You will find the detailed descriptions in the official documentation, while in this tutorial we will refer to the main points, which allow us to:</p>



<ul class="wp-block-list"><li>add email headers</li><li>create plain text and HTML messages</li><li>embed images</li><li>attach files</li><li>send messages via SMTP using password authentication </li></ul>



<h2 class="wp-block-heading"> How to build a simple email </h2>



<p class="wp-block-paragraph">
To create a simple mail, we need to import the necessary classes:</p>



<ul class="wp-block-list"><li><strong>javax.mail.Message</strong> &#8211; an abstract class, creates a message ;<ul><li><strong>javax.mail.internet.MimeMessage </strong>&#8211; its sub-class</li></ul></li><li><strong>javax.mail.MessagingException </strong>&#8211; notifies about possible errors</li><li><strong>javax.mail.PasswordAuthentication</strong> &#8211; requires password authentication for an SMTP server</li><li><strong>javax.mail.Session </strong>&#8211; joins all the properties</li><li><strong>javax.mail.Transport &#8211; </strong>sends message</li><li><strong>javax.mail.internet.InternetAddress</strong> &#8211; to add email addresses</li></ul>



<p class="wp-block-paragraph">Then we need to specify the sending server in properties and set message parameters as follows:</p>



<pre class="wp-block-code"><code>package com.example.smtp;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {
 public static void main(String&#91;] args) {
 // Put recipient’s address
 String to = "test@example.com";

 // Put sender’s address
 String from = "from@example.com";
 final String username = "username@example.com";
 final String password = "yourpassword";

 // Paste host address 
 String host = "smtp.example.com";

 Properties props = new Properties();
 props.put("mail.smtp.auth", "true");
 props.put("mail.smtp.starttls.enable", "true"); 
 props.put("mail.smtp.host", host);
 props.put("mail.smtp.port", "2525");// use the port appropriate for your host 

 // Get the Session object.
 Session session = Session.getInstance(props,
 new javax.mail.Authenticator() {
 protected PasswordAuthentication getPasswordAuthentication() {
 return new PasswordAuthentication(username, password);
 }
 });

 try {
 // Create a default MimeMessage object.
 Message message = new MimeMessage(session);
 
 // Set From: header field 
 message.setFrom(new InternetAddress(from));
 
 // Set To: header field
 message.setRecipients(Message.RecipientType.TO,
 InternetAddress.parse(to));
 
 // Set Subject: header field
 message.setSubject("How to send a simple email in Java");
 
 // Put the content of your message
 message.setText("Hi there, this is my first message sent in Java");

 // Send message
 Transport.send(message);

 System.out.println("Sent message successfully....");

 } catch (MessagingException e) {
 throw new RuntimeException(e);
 }
 }
}
</code></pre>



<p class="wp-block-paragraph"> Here is how this message should look in your test email inbox: </p>



<figure class="wp-block-image"><img src="https://lh6.googleusercontent.com/aufp_sbTnMvhJFlISNiLGC4BaVmCVejKLWQYbuWxegf4Z5rPfFCDIsBJwQYFDEN2c4I4H__PHEnyEl6ahlwUwwLRt9yT_nD7Fl_8ctOTZwXrPY5uEYJ5CXiOsKVCU4_q77SgW6Cg" alt="Send emails in Java"/><figcaption><strong>Send emails in Java</strong></figcaption></figure>



<h2 class="wp-block-heading"> Let’s add HTML content</h2>



<p class="wp-block-paragraph">To build a simple template with text formatting, links, or images, we will use HTML. For this purpose, we will use <strong>SendHTMLEmail</strong> class (unlike SendEmail for a simple message in our previous example) and set <strong>MimeMessage.setContent</strong>(Object, String)<strong>:</strong></p>



<pre class="wp-block-code"><code>package com.example.smtp;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendHTMLEmail {
 public static void main(String&#91; ] args) {
 String to = "johndoe@example.com";

 String from = "yourmail@example.com";
 final String username = "yourusername";
 final String password = "yourpassword"

 String host = "smtp.example.com";

 Properties props = new Properties();
 props.put("mail.smtp.auth", "true");
 props.put("mail.smtp.starttls.enable", "true");
 props.put("mail.smtp.host", host);
 props.put("mail.smtp.port", "2525");

 // Get the Session object.
 Session session = Session.getInstance(props,
 new javax.mail.Authenticator() {
 protected PasswordAuthentication getPasswordAuthentication() {
 return new PasswordAuthentication(username, password);
 }
 });

 try {
 // Create a default MimeMessage object.
 Message message = new MimeMessage(session);

 message.setFrom(new InternetAddress(from));

 message.setRecipients(Message.RecipientType.TO,
 InternetAddress.parse(to));

 message.setSubject("newHTML message");

 message.setContent(
 "<;h1>This is header<;/h1>"
,
 "text/html");

 // Send message
 Transport.send(message);

 System.out.println("Sent message successfully....");

 } catch (MessagingException e) {
 e.printStackTrace();
 throw new RuntimeException(e);
 }
 }
}
</code></pre>



<p class="wp-block-paragraph"> Here is how the result should look in your test email service: </p>



<figure class="wp-block-image"><img src="https://lh4.googleusercontent.com/ANwzhfCjXhhGCymMBYeD6EwfcTKvyj8HFN0Eq08s-sfIEq72u2j_JsTSG8oDTzCHULzaqQc0Jpjy1arBG95FnO_mi9W2A6sT_HicWgpuboiuizmT-N0G554RXnB_sdturY2e2tAQ" alt="Send emails in Java with HTML"/><figcaption><strong>Send emails in Java with HTML</strong></figcaption></figure>



<h2 class="wp-block-heading">How to attach files</h2>



<p class="wp-block-paragraph">You can attach files with the attach file method specified in the MimeBodyPart as follows: </p>



<pre class="wp-block-code"><code>public void attachFile(File file, Multipart multipart, MimeBodyPart messageBodyPart)

 { DataSource source = new FileDataSource(file);

messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());

multipart.addBodyPart(messageBodyPart); }
</code></pre>



<h2 class="wp-block-heading">Other ways to send emails in Java </h2>



<p class="wp-block-paragraph">Above, we have gone through the main capabilities of the native Java email functionality. What other options can you consider?</p>



<p class="wp-block-paragraph">
The most popular alternatives are:</p>



<ul class="wp-block-list"><li>the Spring Framework&#8217;s email library ;</li><li>Apache Common Emails</li><li>Simple Java Mail library</li></ul>



<p class="wp-block-paragraph">It is worth mentioning that all of them are built on top of the JavaMail API. ;</p>



<p class="wp-block-paragraph"> This article on sending emails in Java was originally published on the <a href="https://blog.mailtrap.io/sending-email-using-java/" target="_blank" rel="noreferrer noopener" aria-label="ava was originally published on the Mailtrap blog. (opens in a new tab)">Mailtrap blog. </a></p>



<p class="wp-block-paragraph"> </p>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/authentication-using-javamail-smtp/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '4500'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…