Java Send Email Example

The JavaMail API “pp”-independent(platform and protocol) framework which purpose is to help build messaging and mail applications. It is an optional package and is available with the Java SE platform and is also included in Java EE platform.

The JavaMail can be useful in numerous occasions. For example, it can be used when the user has clicked on “Forgot Password” (by sending an email to the corresponding email set up by the user), signing up for an event in a website (sends further details about it via email), etc.

The main protocols used in JavaMail API

  • SMTP
  • POP
  • IMAP

If you have experience with computer networks, you might have heard some (if not all) of them. But if you do not have experience with computer networks, let me break these protocols down for you.

The application layer

Before jumping into the explanations of the email protocols specifically, let me first introduce to you a simple diagram of the layers in computer networks.

Different protocols in all layers

Network Layers

You can see that SMTP, POP, IMAP and basically all email protocols are under the Application Layer.

The protocols of the Transport Layer provide host-to-host communication services for applications.

The Internet Layer is a group of methods, protocols, and specifications that are used to transport network packets from the originating host across the network, if necessary, to the destination host specified by an IP address.

The protocols in the Network Access Layer provide the means for the system to deliver data to the other devices on a directly attached network.

Now that you know what each layer is for what, we can begin understanding what SMTP, POP, IMAP are in a more in-depth manner.

SMTP

SMTP stands for Simple Mail Transfer Protocol. It is a standard Internet protocol that is used for email transmission across Internet Protocol networks. There is also SMTPS which itself is not a protocol. SMTPS is essentially SMTP connections that are secured by SSL.

POP

POP stands for Post Office Protocol and is an application-layer Internet standard protocol used by local email clients to retrieve email from a remote server over TCP/IP connection. POP supports download and delete requirements for access to remote mailboxes.

IMAP

IMAP stands for Internet Message Access Protocol. It is an Internet standard protocol used by email clients to retrieve email messages from a mail server over a TCP/IP connection. It also allows an email client to access email on a remote mail server. Incoming email messages are sent to an email server that stores messages in the recipient’s email box.




JavaMail architecture

Now it is time to get introduced to the java mail architecture.

How all components co-work

Java Application workflow using JavaMail API

As you can see from the drawing, the JavaMail API is the client layer. It directly correlates to the SPI (Server/Protocol Layer) and then it chooses between SMTP, IMAP or POP and after it has chosen the protocol, it sends the message.

Example of sending an email with JavaMail API

Before we begin, make sure you have installed the necessary .jar files. They can be also found on the Oracle site. Go there and download the latest version. Also, you may want to download fakeSTMP. fakeSTMP is used for testing purposes. For this example, you need to have SMTP installed on your machine.

To be able send mail messages via your gmail account, you should allow unsecure applications (which your application is by gmail’s point of view) in google account security settings.

EmailSender.java

To import all the necessary libraries, you need to import 4 things.

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

After that, I simply create a main method into which I put my variables. The email that is going to receive the email, the sender email and the host.

public class EmailSender {
    public static void main(String[] args) {
        String destinationEmail = "yanicha93@gmail.com";
        String senderEmail      = "yanicha93@gmail.com";
        String host             = "localhost";
    }
}

The next few lines will be responsible for getting the session object.

Properties properties = System.getProperties():
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);

What is the purpose of creating a session object?

The session is the context of how you are going to interact with the mail host. That may include debugging output from the mail host, timeouts and authentication mechanisms.

And then finally, we are sending the actual message.

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(senderEmail));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationEmail));
            message.setSubject("Hello");
            message.setText("Hey, ignore this email, this is just an example");
            Transport.send(message);
            System.out.println("Sent Successfully");
        } 
        catch (MessagingException mex) {
            mex.printStackTrace();
        }

Here we are creating a message, right after that we set who is sending the email (in this case it’s “senderEmail”. After that we simply add the destination email by using message.addRecipient() method. Then we set the subject of the email (you can make it whatever you want) and then we set the text (again, you can make it whatever you want). After all that, we simply send the message.

That’s it! We sent the message.

Complete code snippet:

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

public class EmailSender {
    public static void main(String[] args) {
        String destinationEmail = "yanicha93@gmail.com";
        String senderEmail      = "yanicha93@gmail.com";
        String host             = "localhost";
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        Session session = Session.getDefaultInstance(properties);

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(senderEmail));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationEmail));
            message.setSubject("Hello");
            message.setText("Hey, ignore this email, this is just an example");
            Transport.send(message);
            System.out.println("Sent Successfully");
        } 
        catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

 

Leave a Reply

avatar