Java Mail

This tutorial shows how we can make a connection to a mail server and send an email using the JavaMail API. This API is very useful because normally when we are developing web applications sooner or later we have to send an email to someone and with few lines of this API we can do it.

This is a basic class because it doesn’t allow us to send more than one address and without CCO. To compile this class and to be able to run it you will need to add to your classpath the mail.jar which you can find here.

To set up this class we have to change three main points:

  • First of all we have to know before running the application is which mail server we are going to use. Depending on if you use hotmail, gmail or other one you will have to change the host, port, protocol (smtp or smtps) and if authentication is required. The values show in the program are for a gmail account. Please refer to your mail server details before continue reading.
  • The second part we are going to focus on is the email details itself. Here we are goind to define the subject and the content of the email and of course who is going to receive the email and who has sent it.
  • Lastly we are going to type the name and password account. These details are not encrypted because this class is only to show the email capabilities. However, if this class would be in a real enviorenment all this information should be protected with some cipher algorithms.
package test;

import java.util.Properties;

/**
 * This class sends an email to one person.
 * 
 * @author ProgrammingWorkshop
 * @version 1.0 - 12/02/2011
 */
public class Mail {

	// 1º. Connection details
	private static final String PROTOCOL = "smtps"; // It could be also 'smtp'
	private static final String HOST = "smtp.gmail.com";
	private static final String PORT = "465";
	private static final String AUTH = "true";

	// 2º. Email details
	private String subject = "Email test";
	private String content = "<h1>Hello!</h1></br> This is an email test.</br></br> Thank you. www.programmingworkshop.com.";
	private String from = "XXXXXX";
	private String to = "XXXXXX";

	// 3º. Authentication details
	private static final String USER = "XXXXXX"; // This is our email name
	private static final String PASSWORD = "YYYYYY"; // This is our email password

	/**
	 * This function send an email to one person
	 * 
	 * @param connectionProps
	 *            All the properties needed to establish the connection with the mail sever
	 *            (protocol, host, auth and port)
	 * @param emailProps
	 *            Into this class we have all the information about the email itself (from, to,
	 *            subject and content)
	 * @param user
	 *            This is our email name
	 * @param password
	 *            This is our email password
	 * @return true if the email has been sent correctly. Otherwise it returns false.
	 */
	boolean sendMail(Properties connectionProps, Properties emailProps, String user, String password) {
		try {
			// 0º. Data validation. It is not exhaustive.
			if (connectionProps == null || emailProps == null || user == null || user.equals("")
					|| password == null || password.equals("")) {
				System.out
						.println("Please, make sure you have added all information needed into the arguments");
				return false;
			}

			// 1º. We create a session with the connection details
			Session session = Session.getInstance(connectionProps);
			session.setDebug(false);

			// 2º. We create a message with the email details
			MimeMessage msg = new MimeMessage(session);
			msg.setSubject(emailProps.getProperty("subject"));
			msg.setContent(emailProps.getProperty("content"), "text/html");
			msg.setFrom(new InternetAddress(emailProps.getProperty("from")));
			msg.addRecipient(Message.RecipientType.TO,
					new InternetAddress(emailProps.getProperty("to")));
			// msg.setSentDate(new Date(System.currentTimeMillis()));

			// 3º. Finally we use the authentication details for sending the email
			Transport transport = session.getTransport();
			transport.connect(user, password);
			transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
			transport.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * The main method creates a new instance of the class and set all the parameters to make the
	 * connection with the mail server
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		Mail mail = new Mail();

		// 1º. First of all we have to set the different properties to be able to connect to our
		// mail server
		Properties connectionProps = new Properties();
		connectionProps.setProperty("mail.transport.protocol", PROTOCOL);
		connectionProps.setProperty("mail.smtps.host", HOST);
		connectionProps.setProperty("mail.smtps.auth", AUTH);
		connectionProps.setProperty("mail.smtps.port", PORT);

		// Bear in mind that depending on if you are using a SSL connection or not you could need
		// other different keys. For instance:
		// connectionProps.setProperty("mail.smtp.host", HOST);
		// connectionProps.setProperty("mail.smtp.auth", AUTH);
		// connectionProps.setProperty("mail.smtp.port", PORT);

		// 2º. These are the email details we are going to send.
		Properties emailProps = new Properties();
		emailProps.setProperty("subject", mail.subject);
		emailProps.setProperty("content", mail.content);
		emailProps.setProperty("from", mail.from);
		emailProps.setProperty("to", mail.to);

		// 3º. We call to our function 'sendMail'.
		if (mail.sendMail(connectionProps, emailProps, USER, PASSWORD)) {
			System.out.println("Congratulations!. The email has been sent correctly.");
		} else {
			System.out
					.println("Ups!, we had a little problem connecting with the mail server. Please check your configuration.");
		}
	}
}

I haven’t explained many things in this code because they are self-explanatory but if you have any doubt about it you can refer to the mail API.

If everything is correct we should received an email in our inbox (if we have sent the email to ourselves).

email1

If you get a message like this: “Caused by: java.net.ConnectException: Connection refused: connect” try to check you data configuration and check if you are using mail.smtp or mail.smtps parameters.
Tagged on: ,

Leave a Reply

Your email address will not be published. Required fields are marked *


5 − = three

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>