O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.7. Adding Attachments to an Email in a Servlet

Problem

You want to build an email message with attachments in a servlet.

Solution

Use the JavaMail API for basic email messaging, and the the JavaBeans Activation Framework (JAF) to generate the file attachments.

Discussion

The JAF classes provide fine-grained control over setting up a file attachment for an email message.

Note

If you are using both the JavaMail API and the JAF, make sure to import the packages in your servlet class:

import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;

//class definition continues

The sendMessage( ) method in Example 20-8 creates a new email message (specifically, a new javax.mail.internet.MimeMessage ), adds its text message, and inserts a file attachment inside the message. The method then sends the message using the code you may have seen in Recipe 20.2 and Recipe 20.3:

Transport.send(mailMsg);

To accomplish this, the code creates a container (a javax.mail.Multipart object) and two javax.mail.BodyPart s that make up the the container. The first BodyPart is a text message (used usually to describe the file attachment to the user), while the second BodyPart is the file attachment (in this case, a Microsoft Word file). Then the code sets the content of the MimeMessage to the Multipart. In a nutshell, the MimeMessage (an email message) contains a Multipart, which itself is composed of two BodyParts: the email's text message and an attached file.

Tip

If you want to look at the headers ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required