How do I use java.time.LocalDate class?

JDK8’s LocateDate class is a class that represent information about date. It doesn’t include information about time of day, and it also doesn’t have information about time-zone. An instance of this class is an immutable object.

To create an instance of LocateDate class we can use the of() static method factory. We pass arguments such as the year, month and day into this static factory method. The value for month can be an integer between 1 and 12, or you use the value specified by the java.time.Month enum, such as Month.JANUARY.

The code snippet below show you how to use the LocalDate class.

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;

public class LocalDateDemo {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2014, 9, 7);

        int year = date.getYear();
        Month month = date.getMonth();
        int day = date.getDayOfMonth();

        DayOfWeek dow = date.getDayOfWeek();
        int monthLength = date.lengthOfMonth();
        boolean leapYear = date.isLeapYear();

        System.out.println("Year         = " + year);
        System.out.println("Month        = " + month);
        System.out.println("Day          = " + day);
        System.out.println("Dow          = " + dow);
        System.out.println("Month Length = " + monthLength);
        System.out.println("Leap Year    = " + leapYear);
    }
}

As you can see from the code snippet above, the LocalDate class also provide some methods to get the value from the LocateDate instance. For example, you can obtain the year of the date using the getYear() method. To get the month we can use the getMonth() method which will return the Month enum. And to get the day we can use the getDayOfMonth() method.

We can also get information such as the length of the month and check if the year represented by this LocalDate is a leap year. Running the code snippet above will give you the following result:

Year         = 2014
Month        = SEPTEMBER
Day          = 7
Dow          = SUNDAY
Month Length = 30
Leap Year    = false

Beside using the methods shown above to access values from a LocalDate instance we can also use TemporalField as demonstrated in the code snippet below. Here we call the get() method and pass a temporal field that we want to read using the ChronoField enumeration. This enum implements the TemporalField interface.

int year = date.get(ChronoField.YEAR);
int month = date.get(ChronoField.MONTH_OF_YEAR);
int day = date.get(ChronoField.DAY_OF_MONTH);

System.out.println("year  = " + year);
System.out.println("month = " + month);
System.out.println("day   = " + day);

How do I get today’s date and time?

This example show you how to use the new Date and Time API introduced in JDK 8 to get the current date and time. To get today’s date in this new API you can construct an instance of LocalDate, LocalTime or LocalDateTime and call its toString() method.

All of these classes are located under the new java.time package, and defined as final classes, and because their constructor is declared as a private constructor, it means you can’t use their constructor to create a new instance. But these classes offer some static factory methods to get the value it represents or to create a new instance. For example all of these classes provide a now() method that return the current date, time or date and time information.

Let’s see a complete code snippet in the TodayDateTime example to demonstrate it.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class TodayDateTime {
    public static void main(String[] args) {
        // Obtains the current date from the system clock in the
        // default time-zone.
        LocalDate currentDate = LocalDate.now();
        System.out.println("currentDate = " + currentDate);

        // Obtains the current time from the system clock in the
        // default time-zone.
        LocalTime currentTime = LocalTime.now();
        System.out.println("currentTime = " + currentTime);

        // Obtains the current date-time from the system clock
        // in the default time-zone.
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("currentDateTime = " + currentDateTime);
    }
}

Running this program will give you the following result:

currentDate = 2021-11-14
currentTime = 23:14:47.694204500
currentDateTime = 2021-11-14T23:14:47.694204500

How do I receive mail using POP3?

In this example you will learn how to receive email using POP3. We are going to connect to Gmail server and read the messages in the INBOX folder. There are some steps that you need to do to download this email. Here are the steps:

  1. Setup properties for the mail session.
  2. Creates a javax.mail.Authenticator object.
  3. Creating mail session.
  4. Get the POP3 store provider and connect to the store.
  5. Get folder and open the INBOX folder in the store.
  6. Retrieve the messages from the folder.
  7. Close folder and close store.

These steps can be written as the following code snippet:

package org.kodejava.mail;

import javax.mail.*;
import java.util.Properties;

public class ReadEmail {
    public static final String USERNAME = "kodejava";
    public static final String PASSWORD = "password";

    public static void main(String[] args) throws Exception {
        // 1. Setup properties for the mail session.
        Properties props = new Properties();
        props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.pop3.socketFactory.fallback", "false");
        props.put("mail.pop3.socketFactory.port", "995");
        props.put("mail.pop3.port", "995");
        props.put("mail.pop3.host", "pop.gmail.com");
        props.put("mail.pop3.user", ReadEmail.USERNAME);
        props.put("mail.store.protocol", "pop3");
        props.put("mail.pop3.ssl.protocols", "TLSv1.2");

        // 2. Creates a javax.mail.Authenticator object.
        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(ReadEmail.USERNAME, ReadEmail.PASSWORD);
            }
        };

        // 3. Creating mail session.
        Session session = Session.getDefaultInstance(props, auth);

        // 4. Get the POP3 store provider and connect to the store.
        Store store = session.getStore("pop3");
        store.connect("pop.gmail.com", ReadEmail.USERNAME, ReadEmail.PASSWORD);

        // 5. Get folder and open the INBOX folder in the store.
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);

        // 6. Retrieve the messages from the folder.
        Message[] messages = inbox.getMessages();
        for (Message message : messages) {
            message.writeTo(System.out);
        }

        // 7. Close folder and close store.
        inbox.close(false);
        store.close();
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I create a simple mail client program in Swing?

The code snippet below show you how to create a simple Java Swing application that can be used to send an e-mail. The program allows user to supply the from email address, to email address, the subject and the message of the email. User need to select the available SMTP server to connect to and provide the username and password for authentication to the mail server.

Here is the user interface of this simple email client:

Simple E-mail Client

Simple E-mail Client

The main routine for sending the email is in the SendEmailActionListener class, which is an implementation of an ActionListener interface that will handle email sending process when Send E-mail button is pressed.

package org.kodejava.mail;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Properties;

public class SendEmailClient extends JFrame {
    private final JTextField fromField = new JTextField();
    private final JTextField toField = new JTextField();
    private final JTextField subjectField = new JTextField();
    private final JComboBox<String> mailSmtpHostComboBox = new JComboBox<>();
    private final JTextField usernameField = new JTextField();
    private final JPasswordField passwordField = new JPasswordField();
    private final JTextArea contentTextArea = new JTextArea();

    private SendEmailClient() {
        InitializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            SendEmailClient client = new SendEmailClient();
            client.setVisible(true);
        });
    }

    private void InitializeUI() {
        setTitle("Send E-mail Client");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(new Dimension(500, 500));

        getContentPane().setLayout(new BorderLayout());

        // Header Panel
        JPanel headerPanel = new JPanel();
        headerPanel.setLayout(new GridLayout(6, 2));
        headerPanel.add(new JLabel("From:"));
        headerPanel.add(fromField);

        headerPanel.add(new JLabel("To:"));
        headerPanel.add(toField);

        headerPanel.add(new JLabel("Subject:"));
        headerPanel.add(subjectField);

        headerPanel.add(new JLabel("SMTP Server:"));
        headerPanel.add(mailSmtpHostComboBox);
        mailSmtpHostComboBox.addItem("smtp.gmail.com");

        headerPanel.add(new JLabel("Username:"));
        headerPanel.add(usernameField);

        headerPanel.add(new JLabel("Password:"));
        headerPanel.add(passwordField);

        // Body Panel
        JPanel bodyPanel = new JPanel();
        bodyPanel.setLayout(new BorderLayout());
        bodyPanel.add(new JLabel("Message:"), BorderLayout.NORTH);
        bodyPanel.add(contentTextArea, BorderLayout.CENTER);

        JPanel footerPanel = new JPanel();
        footerPanel.setLayout(new BorderLayout());
        JButton sendMailButton = new JButton("Send E-mail");
        sendMailButton.addActionListener(new SendEmailActionListener());

        footerPanel.add(sendMailButton, BorderLayout.SOUTH);

        getContentPane().add(headerPanel, BorderLayout.NORTH);
        getContentPane().add(bodyPanel, BorderLayout.CENTER);
        getContentPane().add(footerPanel, BorderLayout.SOUTH);
    }

    private class SendEmailActionListener implements ActionListener {
        SendEmailActionListener() {
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Properties props = new Properties();
            props.put("mail.smtp.host", mailSmtpHostComboBox.getSelectedItem());
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.ssl.protocols", "TLSv1.2");

            Session session = Session.getDefaultInstance(props);
            try {
                InternetAddress fromAddress = new InternetAddress(fromField.getText());
                InternetAddress toAddress = new InternetAddress(toField.getText());

                Message message = new MimeMessage(session);
                message.setFrom(fromAddress);
                message.setRecipient(Message.RecipientType.TO, toAddress);
                message.setSubject(subjectField.getText());
                message.setText(contentTextArea.getText());

                Transport.send(message, usernameField.getText(),
                        new String(passwordField.getPassword()));
            } catch (MessagingException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
</dependencies>

Maven Central Maven Central

What are the system properties used for sending email?

Here are a list of system properties that can be used to send an e-mail using the JavaMail API.

Property Default Value Description
mail.host Define the host name of the mail server.
mail.smtp.host Define the host name of the SMTP server; this will overrides the mail.host for SMTP connections only.
mail._protocol_.host Define the host name of the specified protocol (POP, IMAP); this will overrides the mail.host.
mail.user Define the default username sent to all mail servers.
mail._protocol_.user Define the default username for the specified protocol; this will overrides the mail.user for the specified protocol.
mail.smtp.port 25 Define the SMTP port on which the SMTP server is listening.
mail._protocol_.port Default port for the corresponding protocol Define the port on which the servers for the specified protocol is listening.
mail.smtp.starttls.enable Upgrade the regular SMTP connection on the usual port to an encrypted (TLS or SSL) connection.
mail.smtp.connectiontimeout Infinite Define the number of milliseconds to wait for a connection timeout.
mail.debug false Define parameter for disabling or enabling information debugging.
mail.from Define the e-mail address to use in the From header.
mail.mime.charset file.encoding Define the default character set used to send messages.
mail.alternates Define other email address for the current that will not to be included when replying to a message.
mail._protocol_.class Define the fully package qualified class name of the provider for the specified protocol.
mail.transport.protocol First transport provider in the configuration file Define default protocol with which to send messages.
mail.transport.protocol.address-type Define the message transport protocol such as SMTP for the specified address type, for example mail.transport.protocol.rfc822.
mail.replayallcc false Put all recipients in the CC list of the reply message instead of the TO field when replying to all.