Sending Mail with Java

This is for a programmer who is trying send an email as part of a Java program

The JavaMail API

The ability to send an email is not part of the standard JDK.

The jar files you will need

There are two jar files that are needed to send an email. The first is the one for the JavaMail API which is commonly called mail.jar. The second one is the jar file for the JavaBean Activation Framework (JAF), which is activation.jar. JAF can be found at [http://java.sun.com/products/javabeans/glasgow/jaf.html http://java.sun.com/products/javabeans/glasgow/jaf.html] and JavaMail can be found at [http://java.sun.com/products/javamail/ http://java.sun.com/products/javamail/]. The documentation is at [http://java.sun.com/products/javamail/javadocs/index.html http://java.sun.com/products/javamail/javadocs/index.html].

Place the jar files in your CLASSPATH Make sure that the two jar files are in your CLASSPATH variable. You can do this by either adding them in your profile:

export CLASSPATH=$HOME/activation.jar:$HOME/mail.jar

or by adding them to the classpath at compile time. In Eclipse go File/Import/Archive File, and will add it to the project.

Code that does it

You will need:

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

The properties file

You first need to create a properties file. This comes from java.util.Properties. The class has really nice saving and loading to and from XML methods, but we'll ignore these for now. If the server doesn't require authentcation the only property it really needs is the debugging option. I'll add the other properties for the purpose of when we would store the properties in a real file:

Properties props = new Properties();
props.setProperty("mail.subject", "Test email");
props.setProperty("mail.from", "username@cs.byu.edu");
props.setProperty("mail.to", "username@byu.edu");
props.setProperty("mail.debug", "false");

The email itself

The email session gets information from the properties file. There are different email message types and MIME type is the easiest the use:

javax.mail.Session emailSession = javax.mail.Session.getInstance(props);
MimeMessage msg = new MimeMessage(emailSession);
InternetAddress from = new InternetAddress(props.getProperty("mail.from"));
InternetAddress to = new InternetAddress(props.getProperty("mail.to"));
msg.setFrom(from);
msg.setRecipient(Message.RecipientType.TO, to);
msg.setSubject(props.getProperty("mail.subject"));``

Set the text of the msg to be whatever the message needs to be

Sending the message

javax.mail.Transport.send(msg);