Java Reference
In-Depth Information
public
Object
getContent
()
throws
IOException
,
MessagingException
This is reminiscent of the
getContent()
method of
java.net.URL
. However, rather
than relying on the poorly designed content handler mechanism, this
getContent()
method uses the Java Activation Framework, so the behavior is a little more clearly
specified. Most of the time, if the content type is
text/plain
, a
String
will be returned.
If the content type is multipart, then regardless of the subtype, a
javax.mail.Multi
part
object is returned. If the content type is some other type that is recognized by the
underlying
DataHandler
, an appropriate Java object is returned. Finally, if the type is
unrecognized, an
InputStream
is returned.
Another way to read the contents of a part is by writing them onto an
OutputStream
using the
writeTo()
method. If necessary, it will encode the content using Base64,
quoted-printable, or some other format as specified by the
DataHandler
:
public
void
writeTo
(
OutputStream
out
)
throws
IOException
,
MessagingException
In fact, this not only writes the content of this
Part
, it also writes the attributes and
headers of the part.
Example 6-1
used this to provide a simple way of getting an entire
email message in one fell swoop. It's most convenient, though, when you want to send
an entire message to an SMTP server in one method call.
If the part is not just a part, but specifically a
MimeBodyPart
(and most attachments in
regular Internet email will be
MimeBodyPart
s) then you can also use the
saveFile()
method to write the decoded contents of the part into a file:
public
void
saveFile
(
File
file
)
throws
IOException
,
MessagingException
public
void
saveFile
(
String
file
)
throws
IOException
,
MessagingException
Writing the contents of the part
When sending a message, you naturally must set the message's contents. Since email
messages are text, the most straightforward way is just to provide the text of the part
with
setText()
:
public
void
setText
(
String
text
)
throws
MessagingException
,
IllegalWriteException
,
IllegalStateException
The
setText()
method sets the MIME type to
text/plain
. Other objects can be made
into content as well, provided the part has a
DataHandler
that understands how to
convert them to encoded text. This is done with the
setContent()
method:
public
void
setContent
(
Object
o
,
String
type
)
throws
MessagingException
,
IllegalWriteException
,
IllegalStateException
Assuming you're sending Internet email, the concrete
Part
subclass will likely be
Mime
BodyPart
, and in that case then you can also use the
attachFile()
method to encode
the contents of a file into the message: