How to send an Email using JavaMail API

1 Comment

The JavaMail API provides a library which allows us to send and receive Email messages without the need to focus on low-level protocol details.


JavaMail API is not part of the core Java SE JDK, you must download it separately, either directly from Oracle:

http://www.oracle.com/technetwork/java/javamail/

Or if you’re using Maven, simply add the following dependency, which was used for this tutorial:

1
2
3
4
5
<dependency>
  	<groupId>javax.mail</groupId>
  	<artifactId>mail</artifactId>
  	<version>1.4.7</version>
</dependency>

Now the first thing we need to do is to create a Properties instance, which we can use to define many mail server properties, such as the hosts, the port numbers to be used, and many more.

1
Properties properties = new Properties();

Next, we will add few properties, the first will define the SMTP server to be used, the second will define the port number to be used, and the third will define the SMTP protocol.

2
3
4
properties.put("mail.smtp.host", "mail.alibassam.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.transport.protocol", "smtp");

If you would like to check the different options that you can use as properties, here’s a few links:

http://connector.sourceforge.net/doc-files/Properties.html
https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html

Now we need to create a Session instance with the group of properties that we specified.

5
Session session = Session.getInstance(properties);

After that we will use the session to construct a Message object.

6
Message message = new MimeMessage(session);

Now we can fill the fields and add the content. Let’s start by determining the sender and the receiver(s).

7
8
Address from = new InternetAddress("contact@alibassam.com","Ali Bassam");
Address to = new InternetAddress("you@example.com");

In case you wanted to add multiple receivers, you can fill an array of addresses.

9
10
11
12
Address[] addresses = {
     new InternetAddress("someone@example.com"),
     new InternetAddress("another@example.com")
};

Set the sender and receiver(s).

13
14
message.setFrom(from);
message.setRecipient(Message.RecipientType.TO, to);

If there’s multiple receivers.

15
message.setRecipient(Message.RecipientType.TO, addresses);

Notice that we don’t just specify the target address, but also how this address will be used, either in the To: field, Cc: field or Bcc: field.

16
17
18
Message.RecipientType.TO;
Message.RecipientType.CC;
Message.RecipientType.BCC;

And now we can set the Subject, and the Content.

19
20
message.setSubject("JavaMail Test");
message.setText("Write something here");

Finally, we’re going to connect to the host, and send the message using the Transport object.

21
22
23
24
Transport transport = session.getTransport();
transport.connect("contact@alibassam.com", "password");
transport.sendMessage(message, message.getAllRecipients());
transport.close();

And that’s it!

Now let’s put it all together:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.io.UnsupportedEncodingException;
import java.util.Properties;
 
import javax.mail.Address;
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;
 
public class SendEmail {
 
	public static void main(String[] arg) {
			//Start Session with a specified group of Properties
			Properties properties = new Properties();
			properties.put("mail.transport.protocol", "smtp");
			properties.put("mail.smtp.host", "mail.alibassam.com");
			properties.put("mail.smtp.port", "587");
			Session session = Session.getInstance(properties);
			//Create Message
			Message message = new MimeMessage(session);
			//Fields and Contents
			try{
				Address from = new InternetAddress("contact@alibassam.com","Ali Bassam");
				Address to = new InternetAddress("someone@example.com");
				message.setFrom(from);
				message.setRecipient(Message.RecipientType.TO, to);
				message.setSubject("Email from JavaMail API");
				message.setText("Hello, this is the body");
				//Specify Transport
				Transport transport = session.getTransport();
				//Connect to Host (Mail Server)
				transport.connect("contact@alibassam.com", "password");
				//Send Email
				transport.sendMessage(message, message.getAllRecipients());
				//Close Connection
				transport.close();
			}
			catch(UnsupportedEncodingException | MessagingException e) {
				//Catch Exception
			}
	}
}

Authentication

Providing passwords hardcoded in the source code is a bad idea, what you will be probably doing is to ask the user to provide his credentials, JavaMail API allows us to handle this issue using the Authenticator class.

This class will call its getPasswordAuthentication() when it needs the Email and the Password. Since it’s an abstract class, we’re going to create our own subclass.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
 
public class Authenticate extends Authenticator {
 
	@Override
	public PasswordAuthentication getPasswordAuthentication() {
		//You can use JPasswordField in case you're creating a Swing Application
		//Or you can use <h:inputSecret> if you're creating a Web Application
		//Either way, ask the user to provide his email and password
		System.out.println("Please provide your Email and Password");
		//Read the values and return a new instance of the PasswordAuthentication object
		return new PasswordAuthentication(email, password);
	}
}

Now you must make few changes in order to authenticate and send an email.

First you need to add a property which indicates that you would like to use SMTP Authentication.

1
properties.put("mail.smtp.auth","true");

When you the start the Session, make sure to provide an instance of your Authenticator subclass.

2
Session session = Session.getInstance(properties, new Authenticate());

Now instead of retrieving a Transport instance from the session and connecting to the host, simply use the static method of the Transport class to send the message.

3
Transport.send(message);
Categories: Java Tags: Tags: , , , ,

One Reply to “How to send an Email using JavaMail API”

Leave a Reply

%d bloggers like this: