Saturday, February 11, 2012

JavaMail

JavaMail is a standard API for sending emails from Java programs.

To use JavaMail, download javamail.zip from Sun's website.

Explode this zip to get the following jars:
mail.jar
mailapi.jar
pop3.jar
smtp.jar

You will also need to download JavaBeans Actibation Framework - jaf.zip - from Sun's website.

Explode this zip to get the following jar:
activation.jar

Copy these jars to your /lib folder.

In Eclipse, go to Project->Properties->Java Build Path->Libraries->Add Jars
to add the above jars.

Now let us write a class to send an email using JavaMail.

In your /src/org/confucius, create a class EmailSender.java, like this:

 package org.confucius;  

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailSender {

public static void main(String[] args) {
try {
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);

MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("cori@confucius.org"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("arthur@arthur.com"));
message.addRecipient(Message.RecipientType.CC, new InternetAddress("bob@bob.com"));
message.setSubject("Hello JavaMail");
message.setText("Welcome to JavaMail");
message.saveChanges();

Transport transport = session.getTransport("smtp");
transport.connect("localhost", "cori", "changeit");
transport.sendMessage(message, message.getAllRecipients());
transport.close();

} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}

}



What are we doing here?

We are creating an email message, filling its from/to/cc/subject/body fields.

Next we open a SMTP transport session by providing the smtp server (localhost), username and password.

Then we send the email and close the transport session.

To run this code, you will need a SMTP (Email) server running on your machine (localhost).

We recommend "Papercut" - it is a tiny SMTP server that is designed to test programs sending emails. It comes with the server and a email viewer client rolled into one - so you can immediately see all the emails it has received.

Once you have installed Papercut and it is running, you can run EmailSender.java by R-clicking on it in the Eclipse navigator view and selecting Runs As -> Java Application.

You should see an email popup in Papercut.