How do I convert java.util.TimeZone to java.time.ZoneId?

The following code snippet will show you how to convert the old java.util.TimeZone to java.time.ZoneId introduced in Java 8. In the first line of our main() method we get the default timezone using the TimeZone.getDefault() and convert it to ZoneId by calling the toZoneId() method. In the second example we create the TimeZone object by calling the getTimeZone() and pass the string of timezone id. To convert it to ZoneId we call the toZoneId() method.

package org.kodejava.datetime;

import java.time.ZoneId;
import java.util.TimeZone;

public class TimeZoneToZoneId {
    public static void main(String[] args) {
        ZoneId zoneId = TimeZone.getDefault().toZoneId();
        System.out.println("zoneId = " + zoneId);

        TimeZone timeZoneUsPacific = TimeZone.getTimeZone("US/Pacific");
        ZoneId zoneIdUsPacific = timeZoneUsPacific.toZoneId();
        System.out.println("zoneIdUsPacific = " + zoneIdUsPacific);
    }
}

This snippet prints the following output:

zoneId = Asia/Shanghai
zoneIdUsPacific = US/Pacific

To convert the other way around you can do it like the following code snippet. Below we convert the ZoneId to TimeZone by using the TimeZone.getTimeZone() method and pass the ZoneId.systemDefault() which return the system default timezone. Or we can create ZoneId using the ZoneId.of() method and specify the timezone id and then pass it to the getTimeZone() method of the TimeZone class.

package org.kodejava.datetime;

import java.time.ZoneId;
import java.util.TimeZone;

public class ZoneIdToTimeZone {
    public static void main(String[] args) {
        TimeZone timeZone = TimeZone.getTimeZone(ZoneId.systemDefault());
        System.out.println("timeZone = " + timeZone.getDisplayName());

        TimeZone timeZoneUsPacific = TimeZone.getTimeZone(ZoneId.of("US/Pacific"));
        System.out.println("timeZoneUsPacific = " + timeZoneUsPacific.getDisplayName());
    }
}

And here are the output of the code snippet above:

timeZone = China Standard Time
timeZoneUsPacific = Pacific Standard Time

How do I get a list of all TimeZones Ids using Java 8?

To retrieve a list of all available time zones ids we can call the java.time.ZoneId static method getAvailableZoneIds(). This method return a Set of string of all zone ids. The format of the zone id are “{area}/{city}”. You can use these ids of string to create the ZoneId object using the ZoneId.of() static method.

package org.kodejava.datetime;

import java.time.ZoneId;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Set;

public class GetAllTimeZoneIds {
    public static void main(String[] args) {
        Set<String> zoneIds = ZoneId.getAvailableZoneIds();
        for (String id : zoneIds) {
            ZoneId zoneId = ZoneId.of(id);
            System.out.println("id          = " + id);
            System.out.println("displayName = " +
                    zoneId.getDisplayName(TextStyle.FULL, Locale.US));
        }
    }
}

Here are some zone IDs printed out to the console:

id          = Asia/Aden
displayName = Arabian Time
id          = America/Cuiaba
displayName = Amazon Time
id          = Etc/GMT+9
displayName = GMT-9:00
id          = Etc/GMT+8
displayName = GMT-8:00
id          = Africa/Nairobi
displayName = Eastern Africa Time
...
...
...
id          = Europe/Nicosia
displayName = Eastern European Time
id          = Pacific/Guadalcanal
displayName = Solomon Is. Time
id          = Europe/Athens
displayName = Eastern European Time
id          = US/Pacific
displayName = Pacific Time
id          = Europe/Monaco
displayName = Central European Time

How do I get HTTP headers using HttpClient HEAD request?

The HTTP HEAD method is used for reading the headers information of a resource returned when accessing it using the HTTP GET method. Such request can be done before deciding to download a large resource to save bandwidth. The response to a HEAD method should not have a body, in the code below we use the HttpResponse.BodyHandlers.discarding(), which is a response body handler that discards the response body.

In the code snippet below we start by creating an instance of HttpClient, in this example we use the HttpClient.newBuilder().build() method. After creating the HttpClient we create the HttpRequest object. We set the HTTP method to HEAD by calling the method method() and pass a string “HEAD” as the method name and HttpRequest.BodyPublishers.noBody() a request body publisher which sends no request body.

The next step in the code below is to send the request and get the response headers from the HttpResponse object using the headers() method. The map() method of the HttpHeaders object give us a key-values of the headers returned by the server.

package org.kodejava.httpclient;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HeadRequestExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newBuilder().build();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://google.com"))
                .method("HEAD", HttpRequest.BodyPublishers.noBody())
                .build();

        HttpResponse<Void> response = client.send(request,
                HttpResponse.BodyHandlers.discarding());

        // Returns an unmodifiable multi-map view of this HttpHeaders.
        // The map contains key of string, with list of strings as
        // its value.
        HttpHeaders headers = response.headers();
        headers.map().forEach((key, values) ->
                System.out.printf("%s = %s%n", key, values));
    }
}

Here are the HTTP headers we got and printed out to the console screen:

:status = [301]
alt-svc = [quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,h3-T050=":443"; ma=2592000]
cache-control = [public, max-age=2592000]
content-length = [220]
content-type = [text/html; charset=UTF-8]
date = [Wed, 22 Apr 2020 14:41:49 GMT]
expires = [Fri, 22 May 2020 14:41:49 GMT]
location = [https://www.google.com/]
server = [gws]
x-frame-options = [SAMEORIGIN]
x-xss-protection = [0]

How do I read website content using HttpClient?

The HTTP Client API can be used to request HTTP resources over the network. This new API was introduced as a new API in Java 11. It supports HTTP/1.1 and HTTP/2 and also support both synchronous and asynchronous programming models. The code snippet below show you how to use the new API to read the content of a website page.

In the code below we start by creating a new instance of HttpClient using the newHttpClient() static method. This is equivalent to calling newBuilder().build(). This give us an instance of HttpClient with default settings like using the “GET” request method the as the default. Then we create an HttpRequest object using the newBuilder() method, set the request URI and call the build() method to build the HttpRequest object.

Next we send the request by calling the send() method of the HttpClient object. This will sends the given request, blocking if necessary to get the response. The returned HttpResponse object contains the response status, headers, and body as handled by given response body handler.

package org.kodejava.httpclient;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class ReadWebsiteContent {
    public static void main(String[] args) throws Exception {
        // Creates HttpClient object with default configuration.
        HttpClient httpClient = HttpClient.newHttpClient();

        // Creates HttpRequest object and set the URI to be requested, 
        // when not defined the default request method is the GET request.
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://httpie.org/hello"))
                .GET()
                .build();

        // Sends the request and print out the returned response.
        HttpResponse<String> response = httpClient.send(request,
                HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));

        System.out.println("Status Code: " + response.statusCode());
        System.out.println("Headers    : " + response.headers().toString());
        System.out.println("Body       : " + response.body());
    }
}

Here is the content of the website that we read using the code snippet above:

Status Code: 200
Headers    : java.net.http.HttpHeaders@2d299ad6 { {:status=[200], cf-cache-status=[DYNAMIC], cf-ray=[5875b78d5df2eb00-LAX], cf-request-id=[023d710c5b0000eb00b738f200000001], content-length=[116], content-type=[text/x-rst;charset=utf-8], date=[Tue, 21 Apr 2020 08:25:53 GMT], etag=["234b9a1fe19f125356a5396c8cc72d54493a2eef"], expect-ct=[max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"], server=[cloudflare], set-cookie=[__cfduid=d5bdb6d828be3bb85d0f1f4c2ff81041c1587457553; expires=Thu, 21-May-20 08:25:53 GMT; path=/; domain=.httpie.org; HttpOnly; SameSite=Lax]} }
Body       : 

Hello, World! đź‘‹
~~~~~~~~~~~~~~~~

Thank you for trying out HTTPie 🥳

I hope this will become a friendship.

How do I modified the value of LocalDate and LocalTime object?

The easiest way to modify the value of a LocalDate, LocalTime or LocalDateTime object is to use the with() method of the corresponding object. These methods will return a modified version of the object, it doesn’t change the attribute of the original object. All the methods, like withYear(), withDayOfMonth() or the with(ChronoField) of the LocalDate object will return a new object with the modified attribute.

With the LocalTime object you can use the withHour(), withMinute(), withSecond() or the more generic with(ChronoField) method to modified the attribute of a LocalTime object. You can also modified a LocalDateTime object using these with() method. Let’s see the example in the code snippet below.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;

public class ManipulatingDateTime {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2021, 4, 21);
        System.out.println("date1 = " + date1);
        LocalDate date2 = date1.withYear(2020);
        System.out.println("date2 = " + date2);
        LocalDate date3 = date2.withDayOfMonth(10);
        System.out.println("date3 = " + date3);
        LocalDate date4 = date3.with(ChronoField.MONTH_OF_YEAR, 12);
        System.out.println("date4 = " + date4);

        LocalTime time1 = LocalTime.of(1, 5, 10);
        System.out.println("time1 = " + time1);
        LocalTime time2 = time1.withHour(6);
        System.out.println("time2 = " + time2);
        LocalTime time3 = time2.withMinute(45);
        System.out.println("time3 = " + time3);
        LocalTime time4 = time3.with(ChronoField.SECOND_OF_MINUTE, 25);
        System.out.println("time4 = " + time4);

        LocalDate now1 = LocalDate.now();
        System.out.println("now1 = " + now1);
        LocalDate now2 = now1.plusWeeks(1);
        System.out.println("now2 = " + now2);
        LocalDate now3 = now2.minusMonths(2);
        System.out.println("now3 = " + now3);
        LocalDate now4 = now3.plus(15, ChronoUnit.DAYS);
        System.out.println("now4 = " + now4);
    }
}

The output of this code snippet are:

date1 = 2021-04-21
date2 = 2020-04-21
date3 = 2020-04-10
date4 = 2020-12-10
time1 = 01:05:10
time2 = 06:05:10
time3 = 06:45:10
time4 = 06:45:25
now1 = 2021-11-22
now2 = 2021-11-29
now3 = 2021-09-29
now4 = 2021-10-14

These with() methods is the counterpart of the get() methods. Where the get() methods will give you the value of the corresponding LocalDate or LocalTime attribute, the with() method will change the attribute value and return a new object. It didn’t call set because the object is immutable, which means it value cannot be changed.

While with the with() method you can change the value of date time attribute in an absolute way using the plus() or minus() method can help you change the date and time attribute in a relative way. The plus() and minus() method allows you to move a Temporal back or forward a give amount of time, defined by a number plus a TemporalUnit, in this case we use the ChronoUnit enumeration which implements this interface.

How do I created tab delimited data file in Java?

The following code snippet show you how to create a tab delimited data file in Java. The tab character is represented using the \t sequence of characters, a backslash (\) character followed by the t letter. In the code below we start by defining some data that we are going to write to the file.

We create a PrintWriter object, passes a BufferedWritter created using the Files.newBufferedWriter() method. The countries.dat is the file name where the data will be written. Because we are using the try-with-resources the PrintWriter and the related object will be closed automatically when the file operation finishes.

package org.kodejava.io;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class TabDelimitedDataFile {
    public static void main(String[] args) throws IOException {
        List<String[]> data = new ArrayList<>();
        data.add(new String[]{"Afghanistan", "AF", "AFG", "004", "Asia"});
        data.add(new String[]{"Ă…land Islands", "AX", "ALA", "248", "Europe"});
        data.add(new String[]{"Albania", "AL", "ALB", "008", "Europe"});
        data.add(new String[]{"Algeria", "DZ", "DZA", "012", "Africa"});
        data.add(new String[]{"American Samoa", "AS", "ASM", "016", "Polynesia"});
        data.add(new String[]{"Andorra", "AD", "AND", "020", "South Europe"});
        data.add(new String[]{"Angola", "AO", "AGO", "024", "Africa"});
        data.add(new String[]{"Anguilla", "AI", "AIA", "660", "Americas"});
        data.add(new String[]{"Antarctica", "AQ", "ATA", "010", ""});
        data.add(new String[]{"Argentina", "AR", "ARG", "032", "Americas"});

        try (PrintWriter writer = new PrintWriter(
                Files.newBufferedWriter(Paths.get("countries.dat")))) {
            for (String[] row : data) {
                writer.printf("%1$20s\t%2$3s\t\t%3$3s\t\t%4$3s\t\t%5$s",
                        row[0], row[1], row[2], row[3], row[4]);
                writer.println();
            }
        }
    }
}

The output of the code snippet above are:

         Afghanistan     AF     AFG     004     Asia
       Ă…land Islands     AX     ALA     248     Europe
             Albania     AL     ALB     008     Europe
             Algeria     DZ     DZA     012     Africa
      American Samoa     AS     ASM     016     Polynesia
             Andorra     AD     AND     020     South Europe
              Angola     AO     AGO     024     Africa
            Anguilla     AI     AIA     660     Americas
          Antarctica     AQ     ATA     010     
           Argentina     AR     ARG     032     Americas

How do I use TemporalField to access date time value?

The LocalDate and LocalTime are probably the first two classes from the Java 8 Date and Time API that you will work with. An instance of the LocalDate object is an immutable object representing a date without the time of the day and on the other way around the LocalTime object is an immutable object representing a time without the date information.

The LocalDate object have methods to get information related to date such as getYear(), getMonth(), getDayOfMonth(). While the LocalTime object have methods to get information related to time such as getHour(), getMinute(), getSecond(). Beside using those methods we can also access the value of these object using the TemporalField interface. We can pass a TemporalField to the get() method of LocalDate and LocalTime objects. TemporalField is an interface, one of its implementation that we can use to get the value is the ChronoField enumerations.

Let’s see some examples in the code snippet below:

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;

public class DateTimeValueTemporalField {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        System.out.println("Date = " + date);
        System.out.println("Year = " + date.getYear());
        System.out.println("Year = " + date.get(ChronoField.YEAR));

        System.out.println("Month= " + date.getMonth().getValue());
        System.out.println("Month= " + date.get(ChronoField.MONTH_OF_YEAR));

        System.out.println("Date = " + date.getDayOfMonth());
        System.out.println("Date = " + date.get(ChronoField.DAY_OF_MONTH));

        System.out.println("DOW  = " + date.getDayOfWeek().getValue());
        System.out.println("DOW  = " + date.get(ChronoField.DAY_OF_WEEK) + "\n");

        LocalTime time = LocalTime.now();
        System.out.println("Time  = " + time);
        System.out.println("Hour  = " + time.getHour());
        System.out.println("Hour  = " + time.get(ChronoField.HOUR_OF_DAY));

        System.out.println("Minute= " + time.getMinute());
        System.out.println("Minute= " + time.get(ChronoField.MINUTE_OF_HOUR));

        System.out.println("Second= " + time.getSecond());
        System.out.println("Second= " + time.get(ChronoField.SECOND_OF_MINUTE));

        System.out.println("Nano  = " + time.getNano());
        System.out.println("Nano  = " + time.get(ChronoField.NANO_OF_SECOND));
    }
}

The output of the code snippet above are:

Date = 2021-11-22
Year = 2021
Year = 2021
Month= 11
Month= 11
Date = 22
Date = 22
DOW  = 1
DOW  = 1

Time  = 10:52:18.082348200
Hour  = 10
Hour  = 10
Minute= 52
Minute= 52
Second= 18
Second= 18
Nano  = 82348200
Nano  = 82348200

How do I get all Sundays of the year in Java?

You need to create a holiday calendar for your application. One of the functionality is to include all Sundays of the year as a holiday for your calendar. The following code snippet will show you how to get all Sundays of the given year.

First we need to find the first Sunday of the year using the first 3 lines of code in the main() method. After getting the first Sunday we just need to loop to add 7 days using the Period.ofDays() to the current Sunday to get the next Sunday. We stop the loop when the year of the Sunday is different to the current year.

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

import static java.time.temporal.TemporalAdjusters.firstInMonth;

public class FindAllSundaysOfTheYear {
    public static void main(String[] args) {
        // Create a LocalDate object that represent the first day of the year.
        int year = 2021;
        LocalDate now = LocalDate.of(year, Month.JANUARY, 1);
        // Find the first Sunday of the year
        LocalDate sunday = now.with(firstInMonth(DayOfWeek.SUNDAY));

        do {
            // Loop to get every Sunday by adding Period.ofDays(7) to the current Sunday.
            System.out.println(sunday.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
            sunday = sunday.plus(Period.ofDays(7));
        } while (sunday.getYear() == year);
    }
}

The output of this code snippet are:

Sunday, January 3, 2021
Sunday, January 10, 2021
Sunday, January 17, 2021
Sunday, January 24, 2021
Sunday, January 31, 2021
Sunday, February 7, 2021
Sunday, February 14, 2021
Sunday, February 21, 2021
...
Sunday, December 5, 2021
Sunday, December 12, 2021
Sunday, December 19, 2021
Sunday, December 26, 2021

How do I get the first Sunday of the year in Java?

The following code snippet help you find the first Sunday of the year, or you can replace it with any day that you want. To achieve this we can use the TemporalAdjusters.firstInMonth adjusters, these adjusters returns a new date in the same month with the first matching day-of-week. This is used for expressions like ‘first Sunday in January’.

Because we want to get the first Sunday of the year first we create a LocalDate which represent the 1st January 2020. Then we call the with() method and pass the firstInMonth adjusters with the DayOfWeek.SUNDAY to find. Beside using Java 8 date time API, you can also use the old java.util.Calendar class as also shown in the code snippet below. But using the new date time API give you a more readable, simpler and less code to write.

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.util.Calendar;

import static java.time.temporal.TemporalAdjusters.firstInMonth;

public class FirstSundayOfTheYear {
    public static void main(String[] args) {
        // Get the first Sunday of the year using Java 8 date time
        LocalDate now = LocalDate.of(2020, Month.JANUARY, 1);
        LocalDate sunday = now.with(firstInMonth(DayOfWeek.SUNDAY));
        System.out.println("The first Sunday of 2020 falls on: " + sunday);

        // Get the first Sunday of the year using the old java.util.Calendar
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.YEAR, 2020);
        System.out.println("The first Sunday of 2020 falls on: " + calendar.getTime());
        System.out.println("The first Sunday of 2020 falls on: " +
                LocalDate.ofInstant(calendar.getTime().toInstant(), ZoneId.systemDefault()));
    }
}

This code snippet will print out the following output:

The first Sunday of 2020 falls on: 2020-01-05
The first Sunday of 2020 falls on: Sun Jan 05 22:43:37 CST 2020
The first Sunday of 2020 falls on: 2020-01-05

Guide to Send Emails in Java

Java has been ranking as one of the most popular web programming languages for many years. In this tutorial on sending emails in Java, which was originally published on the Mailtrap blog, we will demonstrate how to build HTML emails with images and attachments and send them using an SMTP server.

The main option is to use a Java API for sending and receiving emails via SMTP, POP3, and IMAP. It is implemented as an optional package compatible with any operating system. At the same time, Jakarta Mail is supplied as a part of Jakarta EE and Java EE platforms. In the earlier releases, the mail package was titled “JavaMail API”. However, since July 2019, the Java software has been further developed by the Eclipse Foundation. This is why the email package also got the new name. All main classes and properties are the same for both JavaMail and Jakarta Mail.

In this article, we will describe the main email package properties and will show how to send different types of messages.

Getting Started with Jakarta Mail (JavaMail)

To start working with Jakarta Mail, first of all, you should insert jakarta.mail.jar file into your CLASSPATH environment. You can download it from the (Jakarta Mail project page on GitHub)[https://javaee.github.io/javamail/].

Besides, you can find Jakarta Mail jar files in the Maven repository and add them to your environment with Maven dependencies:

<dependencies>
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>jakarta.mail</artifactId>
        <version>1.6.4</version>
    </dependency>
</dependencies>

Please note that if you use JDK 1.5 or older versions, you will also need an implementation of the JavaBeans Activation Framework.

import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;

Let’s focus on the main steps for preparing HTML email and sending it via an external SMTP server.

Jakarta Mail Classes and Syntax

Before we move to code, let’s review core classes and properties, which are most frequently used for building and sending messages with Jakarta Mail.

Session Class (javax.mail.Session) is the primary one connecting all the properties and defaults. The following methods are used to get the session object:

  • getDefaultInstance() returns the default session

  • public static Session getDefaultInstance/(Properties props)

  • public static Session getDefaultInstance(Properties props, Authenticator auth)

  • getInstance() returns the new session.

  • public static Session getInstance(Properties props)

  • public static Session getInstance(Properties props, Authenticator auth)

Message class (javax.mail.Message) is an abstract class for actually building an email message. We will mostly use its Mime Message (javax.mail.internet.MimeMessage) subclass and its main methods:

  • setFrom(Address[] addresses) sets the “From” header field.

  • public void addFrom(Address[] addresses)

  • addRecipients(Message.RecipientType type, String addresses) adds the given address to the recipient type.

  • public void addRecipient(Message.RecipientType type, Address[] addresses)

  • Message.RecipientType.TO “To”

  • Message.RecipientType.CC “Cc”

  • Message.RecipientType.BCC “Bcc”

  • MimeMessage.RecipientType.NEWSGROUPS “Newsgroups”

  • setSubject(String subject) sets the subject header field.

  • public void setSubject(String subject)

  • setText(String textmessage) sets the text as the message content using text/plain MIME type.

  • public void setText(String textmessage)

  • setContent(Object o, String type) sets this message’s content.

  • public void setContent(Object o, String type)

To send emails via an external SMTP server, use com.sun.mail.smtp package: it is an SMTP protocol provider for the JavaMail API that provides access to an SMTP server.

The main properties are:

  • mail.smtp.user, default username for SMTP.

  • mail.smtp.host, the SMTP server to connect to.

  • mail.smtp.port, the SMTP server port to connect to, if the connect() method doesn’t explicitly specify one. Defaults to 25.

To enable SMTP authentication, set the mail.smtp.auth property or provide the SMTP Transport with a username and password when connecting to the SMTP server.

We will show how to implement it later, when demonstrating code examples.

SMTPMessage class is a specialization of the MimeMessage class for specifying SMTP options and parameters. Simply use this class instead of MimeMessage and set SMTP options using the methods on this class.

  • public SMTPMessage(Session session)

  • Transport ( javax.mail.Transport) is an abstract class for sending messages.

  • Transport.send(message)

To view all classes and their methods, see this section of the Jakarta Mail documentation.

Sending Emails in Java via SMTP

Let’s now review how to implement classes and methods described above and write some Java code to send an email via an external SMTP server.

First of all, we need to define who sends what to whom. So, use the SendEmail public class and set “from” and “to” email addresses and add the subject. With javax.mail.PasswordAuthentication class we will be able to require password authentication to send a message via SMTP server.

In the properties method, we will add the necessary SMTP settings and then create a mail Session object. Afterward, you can create a Message using the MimeMessage.

Finally, send your message with the Transport object.

Don’t forget to add Exceptions. This class enables you to get details on possible errors along with an understanding of how to debug them. The main one is MessagingException. It can be used within javax.mail, javax.mail.internet, and javax.mail.search packages. For example, AddressException for javax.mail.internet will be thrown if you offered a wrongly formatted address.

We will return to debugging a bit later in this post.

How to test emails in Java?

For testing email sending from Java, we will use Mailtrap, an online tool, which helps test, review, and analyze emails sent from dev, QA, or staging environments, without the risk of spamming your customers or colleagues. Once you have tested and verified that everything works properly, change settings for the server you use in production.

Input:

package com.example.smtp;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

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 = "1a2b3c4d5e6f7g";//username generated by Mailtrap
        final String password = "1a2b3c4d5e6f7g";//password generated by Mailtrap

        // Paste host address from the SMTP settings tab in your Mailtrap Inbox
        String host = "smtp.mailtrap.io";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");//it’s optional in Mailtrap
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "2525");// use one of the options in the SMTP settings tab in your Mailtrap Inbox

        // 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("My first message with JavaMail");

            // Put the content of your message
            message.setText("Hi there, this is my first message sent with JavaMail");

            // Send message
            Transport.send(message);

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

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

Output:

Sending HTML Email

To send an HTML email, you should perform the same steps as for sending a simple text message, with only SendHTMLEmail class instead of just SendEmail. Also, you need to set content to the MimeMessage.setContent(Object, String) and indicate text/html type.

Input:

package com.example.smtp;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendHTMLEmail {
    public static void main(String[] args) {
        String to = "johndoe@gmail.com";

        String from = "yourmail@example.com";
        final String username = "1a2b3c4d5e6f7g";//generated by Mailtrap
        final String password = "1a2b3c4d5e6f7g";//generated by Mailtrap

        String host = "smtp.mailtrap.io";

        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("My HTML message");

            // Put your HTML content using HTML markup
            message.setContent(
                "<div><span style=\"color:#57aaca;\">c</span><span style=\"color:#57aec5;\">o</span><span style=\"color:#57b2c0;\">l</span><span style=\"color:#57b6ba;\">o</span><span style=\"color:#57bbb5;\">r</span><span style=\"color:#56bfb0;\">f</span><span style=\"color:#56c3ab;\">u</span><span style=\"color:#56c7a5;\">l</span><span style=\"color:#56cba0;\"> </span><span style=\"color:#5ec3ab;\">m</span><span style=\"color:#65bbb6;\">e</span><span style=\"color:#6db3c1;\">s</span><span style=\"color:#75accd;\">s</span><span style=\"color:#7da4d8;\">a</span><span style=\"color:#849ce3;\">g</span><span style=\"color:#8c94ee;\">e</span></div>", "text/html");

            // Send message
            Transport.send(message);

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

        } catch (MessagingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

Output:

In Mailtrap, you can also check the raw data of your message as well as its HTML source on separate tabs.

If you would like your message to contain both HTML and plain text, you need to build it using a MimeMultipart(“alternative”) object. You should create two different parts manually and insert them separately: text/plain body part as the first part in the multipart the text/html body part as the second one.

HTML Email with Images in Java

To add an image to your HTML emails in Jakarta Mail, you can choose any of three regular options: CID, base64 image, or linked image.

To embed a CID image, you need to create a MIME multipart/related message:

Multipart multipart = new MimeMultipart("related");

MimeBodyPart htmlPart = new MimeBodyPart();
//add reference to your image to the HTML body <img src="cid:some-image-cid" alt="img" />
htmlPart.setText(messageBody, "utf-8", "html");
multipart.addBodyPart(htmlPart);

MimeBodyPart imgPart = new MimeBodyPart();
// imageFile is the file containing the image
imgPart.attachFile(imageFile);
// or, if the image is in a byte array in memory, use
// imgPart.setDataHandler(new DataHandler(
// new ByteArrayDataSource(bytes, "image/whatever")));

imgPart.setContentID("<some-image-cid>");
multipart.addBodyPart(imgPart);

message.setContent(multipart);

For a base64, or inlined image, include the encoded image data in the HTML body:

<img src="data:image/jpeg;base64,base64-encoded-data-here" />

But remember that each Base64 digit represents 6 bits of data, so your actual image code will be pretty long. Besides, it affects the overall size of the HTML message, so it’s better not to inline large images.

The simplest way to add an image is just linking to the image hosted on some external server. Refer to your image as a link in the HTML body with an “img” tag:

<img src="https://blog.mailtrap.io/wp-content/uploads/2018/11/blog-illustration-email-embedding-images.png" alt="img" />

Sending an Email with Attachments

To attach any type of files to your message, you need to build a MIME multipart message and indicate the attachFile method in the MimeBodyPart.

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

Debug Jakarta Mail

Debugging plays a critical role in testing of email sending. In Jakarta Mail it’s pretty straightforward. Set debug to true in the properties of your email code:

props.put("mail.debug", "true");

As a result, you will get a step by step description of how your code is executed. If any problem with sending your message appears, you will instantly understand what happened and at which stage.

Here is how our HTML message debug output looks:

DEBUG: Jakarta Mail version 1.6.4
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: need username and password for authentication
DEBUG SMTP: protocolConnect returning false, host=smtp.mailtrap.io, user=diana, password=<null>
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.mailtrap.io", port 2525, isSSL false
220 mailtrap.io ESMTP ready
DEBUG SMTP: connected to host "smtp.mailtrap.io", port: 2525
EHLO DESKTOP-NLP1GG8
250-mailtrap.io
250-SIZE 5242880
250-PIPELINING
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250-AUTH PLAIN LOGIN CRAM-MD5
250 STARTTLS
DEBUG SMTP: Found extension "SIZE", arg "5242880"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN CRAM-MD5"
DEBUG SMTP: Found extension "STARTTLS", arg ""
STARTTLS
220 2.0.0 Start TLS
EHLO DESKTOP-NLP1GG8
250-mailtrap.io
250-SIZE 5242880
250-PIPELINING
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250 AUTH PLAIN LOGIN CRAM-MD5
DEBUG SMTP: Found extension "SIZE", arg "5242880"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN CRAM-MD5"
DEBUG SMTP: protocolConnect login, host=smtp.mailtrap.io, user=1e2b3c4d5e6f7g, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM XOAUTH2 
DEBUG SMTP: Using mechanism LOGIN
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<yourmail@example.com>
250 2.1.0 Ok
RCPT TO:<johndoe@gmail.com>
250 2.1.0 Ok
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   johndoe@gmail.com
DATA
354 Go ahead
Date: Tue, 30 Jul 2019 17:19:31 +0200 (EET)
From: yourmail@example.com
To: johndoe@gmail.com
Message-ID: <20132171.0.1548256771226@DESKTOP-NLP1GG8>
Subject: My HTML message
MIME-Version: 1.0
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit

<div><span style="color:#57aaca;">c</span><span style="color:#57aec5;">o</span><span style="color:#57b2c0;">l</span><span style="color:#57b6ba;">o</span><span style="color:#57bbb5;">r</span><span style="color:#56bfb0;">f</span><span style="color:#56c3ab;">u</span><span style="color:#56c7a5;">l</span><span style="color:#56cba0;"> </span><span style="color:#5ec3ab;">m</span><span style="color:#65bbb6;">e</span><span style="color:#6db3c1;">s</span><span style="color:#75accd;">s</span><span style="color:#7da4d8;">a</span><span style="color:#849ce3;">g</span><span style="color:#8c94ee;">e</span></div>
.
250 2.0.0 Ok: queued
DEBUG SMTP: message successfully delivered to mail server
QUIT
221 2.0.0 Bye
Sent message successfully....

Need More Options?

In this post, we have guided you through the main Jakarta Mail use cases and options. Should you experience any difficulties with installing, implementing, or using this package, refer to the Jakarta Mail FAQ.

Indeed, constructing transactional emails to send from your Java app with Jakarta Mail API takes time. Alternatively, you can consider options for simplified email sending in Java. For example, the Spring Framework or Apache Common Emails are quite popular, while the Play Framework offers a plugin for sending emails. Simple Java Mail is one of the simplest libraries ever – in fact, it is a wrapper around JavaMail API.