Wednesday, 20 November 2019

Textual description of firstImageUrl

How to Send emails in Java

Today we will discuss how to send emails from your Java app. 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).


What is JavaMail:

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 here.
 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. To download the latest version, go to the Jakarta Mail Implementation page on GitHub. You will need jakarta.mail.jar file: insert it in your CLASSPATH environment then. Alternatively, you can add it with Maven dependencies as follows:
    <dependencies>
            <dependency>
                <groupId>com.sun.mail</groupId>
                <artifactId>jakarta.mail</artifactId>
                <version>1.6.4</version>
            </dependency>
        </dependencies>

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:


  • add email headers 
  • create plain text and HTML messages 
  • embed images
  • attach files 
  • send messages via SMTP using password authentication

How to build a simple email

To create a simple mail, we need to import the necessary classes:


  • javax.mail.Message - an abstract class, creates a message 
  • javax.mail.internet.MimeMessage - its sub-class
  • javax.mail.MessagingException - notifies about possible errors
  • javax.mail.PasswordAuthentication - requires password authentication for an SMTP server
  • javax.mail.Session - joins all the properties
  • javax.mail.Transport - sends message
  • javax.mail.internet.InternetAddress - to add email addresses


Then we need to specify the sending server in properties and set message parameters as follows:

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[] 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);
      }
   }
}

Here is how this message should look in your test email inbox:













Let’s add HTML Content:

To build a simple template with text formatting, links, or images, we will use HTML. For this purpose, we will use SendHTMLEmail class (unlike SendEmail for a simple message in our previous example) and set MimeMessage.setContent(Object, String):



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[ ] 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);
      }
   }


}

Here is how the result should look in your test email service:














How to attach files :
You can attach files with the attachFile method specified in the MimeBodyPart as follows: 
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);

}

Other ways to send emails in Java:

Above, we have gone through the main capabilities of the native Java email functionality. What other options can you consider?
The most popular alternatives are:
  • add email headers
  • Apache Common Emails
  • Simple Java Mail library

It is worth mentioning that all of them are built on top of the JavaMail API. This article on sending emails in Java was originally published on the Mailtrap blog.