background image

Attachments Example

<< The Arguments Field | Running Attachments Example >>
<< The Arguments Field | Running Attachments Example >>

Attachments Example

Attachments Example
The example Attachments.java, based on the code fragments in the sections
"Creating an
AttachmentPart
Object and Adding Content" on page 601
and
"Accessing an AttachmentPart
Object" on page 603
, creates a message that has a text attachment and an image attachment. It
then retrieves the contents of the attachments and prints the contents of the text attachment.
You will find the code for the Attachments class in the following directory:
tut-install/javaeetutorial5/examples/saaj/attachments/src/
Attachments
first creates a message in the usual way. It then creates an AttachmentPart for the
text attachment:
AttachmentPart attachment1 = message.createAttachmentPart();
After it reads input from a file into a string named stringContent, it sets the content of the
attachment to the value of the string and the type to text/plain and also sets a content ID.
attachment1.setContent(stringContent,
"text/plain");
attachment1.setContentId(
"attached_text");
It then adds the attachment to the message:
message.addAttachmentPart(attachment1);
The example uses a javax.activation.DataHandler object to hold a reference to the graphic
that constitutes the second attachment. It creates this attachment using the form of the
createAttachmentPart
method that takes a DataHandler argument.
// Create attachment part for image
URL url = new URL(
"file:///../xml-pic.jpg");
DataHandler dataHandler = new DataHandler(url);
AttachmentPart attachment2 = message.createAttachmentPart(dataHandler);
attachment2.setContentId(
"attached_image");
message.addAttachmentPart(attachment2);
The example then retrieves the attachments from the message. It displays the contentId and
contentType
attributes of each attachment and the contents of the text attachment.
Building and Running the Attachments Example
The Attachments class takes a text file as an argument. You can specify any text file. The
attachments
directory contains a file named addr.txt that you can use.
Code Examples
The Java EE 5 Tutorial · September 2007
622