Send Email with Java

On March 3, 2011, in Java, Programming, Software Development, by LuCuS

Java Send MailSending emails can be a great addition to any application. I try to include email support in as many of my programs as possible, especially my automation systems. It is very beneficial to have your application send you notifications of what is going on and it doesn’t take much to do it. I especially like having my applications send me emails when something goes wrong. This keeps me informed of any defects my applications may have and provides me with an inside look of what caused the problem, even when I’m not there testing it myself. And, in this day and age, you can even have your application send emails directly to your cellphone. I don’t think I need to go any further on the advantages of adding email capabilities to your application. So, we’re going to dive right in and start learning how to send emails in Java.

In order to send emails from Java, you will need to select a library to help you since Java doesn’t support email natively. There are hundreds of Java libraries out there that assist in sending emails, but I personally like to use what comes with Eclipse; javax mail. Go ahead and fire up Eclipse and either create a new Java project or open an existing project. Before doing anything else, we need to include the javax mail library to our application. You can find the JAR file for javax mail in your Eclipse > plugins folder. To add it, click on Project > Properties… from the menu bar. You should now see a dialog window for your project’s properties. In the panel on the left, click on “Java Build Path” and in the panel on the right, click on the “Libraries” tab.

Now, click on the “Add External JARs…” button to open a file dialog window. Browse out to your Eclipse > plugins folder and locate the javax.mail_xxxxxx.jar file where “xxxxxx” is the version number. Select the jar file and click the “OK” button. This will add the library to your application so that you can utilize it later.

Once you have added the JAR file for javax mail, create a new Java class with a main constructor. I called mine “SendMail”. After you’ve created a new Java class and it has opened, you will need to add imports for the packages we’ll be using. The first package is “java.util.Properties”. This object provides us with a way to define properties for storing the protocol, host, user, and password that we will need to make our mail program work. The next imports we need to add are for our mail package. I’ll explain each of these later. For now, we’ll just include the imports.

import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

Inside our main method, we need to instantiate a new instance of the Properties object and set our properties. We do this using the setProperty method which takes two parameters. The first parameter is the name of the property and the second is the property value. As mentioned before, we need to define properties for the mail protocol, mail host, user, and password. For sending mail, we’re going to use the SMTP protocol. SMTP is short for “simple mail transfer protocol”. The host property will need to be the address of a server that is capable of sending outgoing emails. For my personal projects, I usually either use the address of my personal mail server or the address for the mail server of my ISP. You can also use free anonymous outbound servers, but I wouldn’t recommend using these since most of them are blocked by other mail servers.

The last two properties we need to set are the username and password of a valid user on our outgoing mail server. Most mail servers require us to authenticate against them before we can use them. This allows the server to track and log where emails originate from and prevents any unauthorized usage of the server. For this example, I’m going to just use some fake property values, but the property names are correct. So, be sure to type the names as I have and replace the values with those that match your scenario. Also, be sure to use “smtp” as the value for the protocol property.

Properties props = new Properties();
props.setProperty(“mail.transport.protocol”, “smtp”);
props.setProperty(“mail.host”, “mail.yourserver.com”);
props.setProperty(“mail.user”, “you@youraddress.com”);
props.setProperty(“mail.password”, “YourPassword”);

The next thing we need to do is to define a  session for our mail application to work with. We will do this using the javax.mail.Session object. Just like the different libraries for sending mail, there are several libraries for managing sessions. So, be sure to use the Session object that comes with javax mail. Define your mail session by getting the default instance from the Session object and pass in the properties object as the first parameter. Since we defined our authenticator in our properties (username and password), we will simply set the second parameter to null. After you’ve defined your session, go ahead and setup the Transport object by adding an instance for it and setting it to the session transport.

Session mailSession = Session.getDefaultInstance(props, null);
Transport transport = mailSession.getTransport();

We are now ready to setup our mail message. We are going to use the MimeMessage object to build our mail message by creating a new instance and passing in our session as a parameter. After we have a new MimeMessage instance, we will construct it by filling in the appropriate attributes. Think of the MimeMessage just as you would a normal email. Every email needs to have a “from” address and a list of recipients. Although the subject and body are not required, we’re going to fill them in anyways. Besides, what would an email be without a body? Not to mention, adding a subject makes for better email management. So, to build our message, we will be passing four parameters.

The first parameter we will be passing to our MimeMessage is the “from” address. It needs to be a valid address. So, to validate that we have structured our address correctly, we will run it through the InternetAddress object. The InternetAddress object accepts a String as its’ parameter.

new InternetAddress(“you@youraddress.com”)

The second parameter we will be passing is the address of the intended recipient. We will use the addRecipient method to do this since it allows us to add as many recipients as we want. The addRecipient method takes two parameters; a RecipientType and the address itself which also needs to be ran through the InternetAddress object.

The last two parameters we will be passing to our MimeMessage are the subject and body content. The subject is extremely simple since it only takes a String object as its’ only parameter. The body content on the other hand can be a little more flexible. For our example, we’re simply going to pass a string as the content. However, the content can accept any type of Object as long as you set the content type accordingly.

You should now have something like this:

MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(“you@youraddress.com”));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(“recipient@someaddress.com”));
message.setSubject(“Email Test”);
message.setContent(“This is a test of the emergency broadcast system.”“text/plain”);

Now that we have ourselves a message, all we have left to do is to send it. That’s where our Transport object that we defined earlier comes in. We open a connection to our mail server by using the Transport connect method. Don’t worry about passing it any parameters since we already defined our username and password in our properties object earlier. After we have connected to our mail server, we will use the sendMessage method to do just that, send the message. To make our sendMessage method work, we need to pass it our message and recipient list which we will get from our message object. After that, the only thing we have left to do is to close our transport object.

transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();

And we’re done. That’s all we have to do to successfully send an email from our application. Which reminds me, if you plan on sending email from inside your applications, I would recommend setting it up as a public method that accepts a “from” address, list of recipients, subject, and body content as parameters.

public void sendEmail(String from, String[] recipients, String subject, String content)

That way, you don’t have to duplicate any code and can simply reuse the same method every time you wish to send an email. I went ahead and did the work for you below. I even added the code to show you how to include multiple recipients using a String Array.

import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {
	public static void main(String[] args) throws Exception {
		// Define our mail recipients
		String[] recipients = {"recipient@someaddress.com"};
		
		// Call our sendEmail method
		sendEmail("you@youraddress.com", recipients, "Email Test", 
			"This is a test of the emergency broadcast system.");
	}
	
	public static void sendEmail(String from, String[] recipients, String 
		subject, String content) throws Exception	{

		// Add some properties for our mail server connection
	      Properties props = new Properties();
	      props.setProperty("mail.transport.protocol", "smtp");
	      props.setProperty("mail.host", "mail.yourserver.com");
	      props.setProperty("mail.user", "YourUsername");
	      props.setProperty("mail.password", "YourPassword");

	      // Build a session for our mail app to use
	      Session mailSession = Session.getDefaultInstance(props, null);
	      
	      // Define a way to send our email
	      Transport transport = mailSession.getTransport();

	      // Build the email message
	      MimeMessage message = new MimeMessage(mailSession);
	      message.setFrom(new InternetAddress(from));

	      // Iterate a list of recipients and add each to the message 
		// recipients list
	      for(int i = 0; i < recipients.length; i++){
	    	  message.addRecipient(Message.RecipientType.TO, new 
			InternetAddress(recipients[i]));
		}

	      message.setSubject(subject);
	      message.setContent(content, "text/plain");

	      // Connect to our mail server
	      transport.connect();
	      
	      // Send the email message
	      transport.sendMessage(message, 
			message.getRecipients(Message.RecipientType.TO));
	      
	      // Close our mail server connection
	      transport.close();
	}
}

Related Posts

Tagged with:  

Leave a Reply