With software automating every action possible, why not automate the distribution of pertinent information to end-users/customers via email? The JavaMail API (currently in version 1.4.3) can support this development in a protocol-independent manner and remain platform independent as always.
Let’s skip the boring theory and jump right into a demo program, which you can use to send an email with a predetermined set of information. Here’s the JavaMail code for sending the email:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
class EmailClient
{
final String emailInfo = “EmailInfo.properties”;
Properties properties = new Properties();
public static void main(String args[])
{
EmailClient emailClient = new EmailClient ();
emailClient.sendEmail();
}
private void sendEmail()
{
try{
//This is required to load all the properties
FileInputStream fileInputStream = new FileInputStream(emailInfo);
properties.load(fileInputStream);
fileInputStream.close();
}catch(IOException ioe)
{
//throw IOException of your choice.
//can end here
}
System.out.println(“Email properties read successfully.”);
String smtpAddress = properties.getProperty(“smtpAddress”);
String fromAddress = properties.getProperty(“fromAddress”);
String toAddress = properties.getProperty(“toAddress”);
String emailSubject = properties.getProperty(“emailSubject”);
String emailBody = properties.getProperty(“emailBody”);
Properties props = new Properties();
props.put(“mail.smtp.host”, smtpAddress);
props.put(“mail.from”, fromAddress);
Session session = Session.getInstance(props, null);
try
{
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setRecipients(Message.RecipientType.TO,toAddress);
mimeMessage.setSentDate(new Date());
mimeMessage.setSubject(emailSubject);
mimeMessage.setText(emailBody);
System.out.println(“Sending e-mail…”);
Transport.send(mimeMessage);
System.out.println(“e-mail sent.”);
}
catch(MessagingException me)
{
System.out.println(“e-mail send failed.”);
me.getMessage();
}
}
}
The code is fairly simple to understand:
- We have loaded the properties for the email to be sent from a properties file. This could come from any other source, such as hardcoded values, a database, a user interface, etc.
- The processed information is updated to the MimeMessage object, which is the actual email object. (The MIME, or Multipurpose Internet Mail Extensions, is an Internet standard that specifies how messages must be formatted for interoperability.)
- MimeMessage takes a session argument, which can either be created (as in this application) or refer to the default session.
- The session—important in any context and used here for the email—is established using the properties
mail.smtp.host
andmail.from
.
- We set other details, such as the date, subject, and the body of the email, which will be used when the email is sent.
- Finally, the email is dispatched using the
send()
method of the Transport class.
The entire email information is made available in a properties file. Here are the contents of the properties file for this application:
smtpAddress=smtp.server.address
fromAddress=myself@me.com
toAddress=someone@you.com
emailSubject=First email
emailBody=My first email
As stated previously, the source of the required information can vary. In this case, we can modify the entries at will without recompiling the code to experiment. By the way, holding configurable information in properties files is a standard programming practice.
Advanced Emails
After reading the previous section, sending emails should seem simple. Now, let’s add more advanced features to the application. Don’t you need attachments with email? The following code creates just that.
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
import java.io.*;
class SendAdvancedEmail
{
final String emailInfo = “EmailInfo.properties”;
Properties properties = new Properties();
public static void main(String args[])
{
SendAdvancedEmail sendAdvancedEmail = new SendAdvancedEmail ();
sendAdvancedEmail.sendEmail();
}
private void sendEmail()
{
try{
//This is required to load all the properties
FileInputStream fileInputStream = new FileInputStream(emailInfo);
properties.load(fileInputStream);
fileInputStream.close();
}catch(IOException ioe)
{
//throw IOException of your choice.
//can end here
}
System.out.println(“Email properties read successfully.”);
String smtpAddress = properties.getProperty(“smtpAddress”);
String fromAddress = properties.getProperty(“fromAddress”);
String toAddress = properties.getProperty(“toAddress”);
String emailSubject = properties.getProperty(“emailSubject”);
String emailBody = properties.getProperty(“emailBody”);
Properties props = new Properties();
props.put(“mail.smtp.host”, smtpAddress);
props.put(“mail.from”, fromAddress);
Session session = Session.getInstance(props, null);
try
{
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setRecipients(Message.RecipientType.TO,toAddress);
mimeMessage.setSentDate(new Date());
mimeMessage.setSubject(emailSubject);
//The following is required to add attachments
MimeMultipart multipart = new MimeMultipart();
//Creating the text part of the email message
BodyPart bodyPart = new MimeBodyPart();
//The type is set to “text/plain”
bodyPart.setText(emailBody);
//Creating the attachment part of the email message
BodyPart attachment = new MimeBodyPart();
DataSource source = new FileDataSource(emailInfo);
attachment.setDataHandler(new DataHandler(source));
attachment.setFileName(emailInfo);
//attachment.setContent(properties, “text/html”);
//Now combining the email message and the attachment
multipart.addBodyPart(bodyPart);
multipart.addBodyPart(attachment);
//Setting the message with the multipart just created
mimeMessage.setContent(multipart);
System.out.println(“Sending e-mail…”);
Transport.send(mimeMessage);
System.out.println(“e-mail sent.”);
}
catch(MessagingException me)
{
System.out.println(“e-mail send failed.”+me);
me.getMessage();
}
}
}
The important difference between this code listing and the one for sending email in the previous section is the process of building the message body, which is now capable of adding a file as an attachment. The Multipart class is actually split into two sections, the message part and the attachment. The properties are actually the same as for the previous code listing.
You could use Multipart instead of MimeMultipart, but be aware that Multipart is an abstract class and hence requires you to create an instance of MimeMultipart. It’s a similar case with MimeMessage. You can use Message, which also is an abstract class. Understanding all the classes used here will help you familiarize yourself with the mail package.
Covering all the other classes and methods in the JavaMail API is beyond the scope of this article. In fact, the code samples do not completely handle all the email scenarios that can occur. The listings are used only as explanations of how to use the code; you can enhance them with other necessary capabilities. Different applications would need these code fragments integrated in different ways that suit their particular requirements. If you were to build a complete email server and client, for example, you would need to understand all the JavaMail classes and methods in detail.
However, the article has provided enough information for you to experiment with sending and receiving emails. Just remember these important tips:
- The details in the properties file must be accurate to achieve the desired results.
- Download the JavaMail and the JavaBeans Activation Framework JARs. Ensure that you have
mail.jar
andactivation.jar
in your classpath.
- As of writing this article, I understand that the JavaMail API is integrated into Java SE 6.