Java Reference
In-Depth Information
Attaching files (or other documents) to messages you send is more complicated. To
attach a file to a message, you first have to wrap the data in a
BodyPart
object and add
it to the
Multipart
using one of the two
addBodyPart()
methods:
public
void
addBodyPart
(
BodyPart
part
)
throws
IllegalWriteException
,
MessagingException
public
void
addBodyPart
(
BodyPart
part
,
int
index
)
throws
IllegalWriteException
,
MessagingException
The first variant simply appends the part to the end of the message. The second variant
adds the given part at the specified position. If the position is greater than the number
of parts in the message, the part is simply added to the end. If it's added somewhere in
the middle, this may cause the positions of other parts to change. If the message can't
be changed, an
IllegalWriteException
is thrown.
The tricky part is creating the
BodyPart
object. You first need to guess a reasonable
MIME content type for the file (
text/plain
and
application/octet-stream
are the
most common types). Next, read the file and convert it into some class of Java object.
Then install a
javax.activation.DataHandler
class that knows how to convert your
data class according to your chosen MIME type. Once you've done all this, you can
create a new
MimeBodyPart
object and use the various methods of the
Part
interface to
set attributes such as the filename and the content disposition.
There are also two
removeBodyPart()
methods that delete a specified part from the
message, although these aren't as commonly used:
public
boolean
removeBodyPart
(
BodyPart
part
)
throws
IllegalWriteException
,
MessagingException
public
void
removeBodyPart
(
int
index
)
throws
IndexOutOfBoundsException
,
MessagingException
If the message can't be changed, an
IllegalWriteException
is thrown. If the specified
index doesn't identify a part, an
IndexOutOfBoundsException
is thrown. If the specified
part isn't present in the message, a
MessagingException
is thrown.
MIME Messages
MIME was designed mainly for Internet email and specifically organized to be
backward-compatible with existing protocols and software. Therefore, a typical Internet
email message is in fact a MIME message. The only concrete subclass of
Message
in the
JavaMail API is
javax.mail.internet.MimeMessage
:
public
class
MimeMessage
extends
Message
implements
MimePart
This class declares almost 70 public and protected methods. However, almost all of these
either override methods from the
Message
superclass or implement methods declared