Java Reference
In-Depth Information
public
void
attachFile
(
File
file
)
throws
IOException
,
MessagingException
public
void
attachFile
(
String
file
)
throws
IOException
,
MessagingException
public
void
attachFile
(
File
file
,
String
contentType
,
String
encoding
)
throws
IOException
,
MessagingException
public
void
attachFile
(
String
file
,
String
contentType
,
String
encoding
)
throws
IOException
,
MessagingException
Finally, multiple parts can be added to a part by wrapping them in a
Multipart
object
and passing that to
setContent()
:
public
void
setContent
(
Multipart
mp
)
throws
MessagingException
,
IllegalWriteException
,
IllegalStateException
In this case, the entire message typically has a content type such as
multipart/mixed
,
multipart/signed
, or
multipart/alternative
. The individual parts of the message
are all enclosed in one envelope but each part of the message has its own content type,
content encoding, and data. The multiple parts may be used to present different forms
of the same document (e.g., HTML and plain-text mail), a document and metainfor‐
mation about the document (e.g., a message and the MD5 digest of the message), or
several different documents (e.g., a message and several attached files). The next section
expands on this process.
Multipart Messages and File Attachments
The way all the different text and binary file types are encoded into raw text that can be
passed through 7-bit email gateways is fairly ingenious and rather detailed. Fortunately,
the JavaMail API shields you from those details, interesting as they are. To send a mul‐
tipart message using the JavaMail API, all you have to do is add the parts to a
MimeMultipart
object, then pass that object to the
Message
's
setContent()
method. To
receive a multipart message, you simply process each of the parts individually.
Most of the methods for building and deconstructing multipart messages are in the
abstract
javax.mail.Multipart
class:
public
abstract
class
Multipart
extends
Object
However, since this class is abstract, you'll generally start with a javax.mail.inter‐
net.MimeMultipart object instead:
public
class
MimeMultipart
extends
Multipart
Each part you add to a
Multipart
is an instance of the abstract
javax.mail.Body
Part
class that implements the
Part
interface of the last section:
public
abstract
class
BodyPart
extends
Object
implements
Part
In Internet email, the concrete subclass of
BodyPart
you'll use is javax.mail.inter‐
net.MimeBodyPart:
public
class
MimeBodyPart
extends
BodyPart
implements
MimePart