Java Reference
In-Depth Information
Most of the methods you need in the
MimeBodyPart
and
BodyPart
classes are the ones
you're already familiar with from the
Part
interface, methods such as
setContent()
and
setDataHandler()
. There are also three methods to read the contents of a
Multipart
object:
public
String
getContentType
()
public
int
getCount
()
throws
MessagingException
public
BodyPart
getBodyPart
(
int
index
)
throws
IndexOutOfBoundsException
,
MessagingException
The
getContentType()
method returns the MIME media type of the entire
Multipart
, which is typically something like
multipart/mixed
or
multipart/
alternative
. This is not the same as the MIME types of the individual parts, which are
something like
text/plain
or
image/gif
.
The
getCount()
method returns the number of parts in this
Multipart
. The
getBody
Part()
method returns a particular part. Parts are numbered starting at 0, like the
components of an array.
Example 7-5
is very similar to
Example 7-4
,
AllHeader
Client
. However,
Example 7-5
adds the necessary code to handle the body of the mes‐
sage. If the message is a single-part message, it's simply printed on
System.out
; but if
the message has multiple parts, each part is handled separately. If the part has a multipart
content type itself,
processMultipart()
is called recursively. If the part has no filename,
does not have the disposition
Part.ATTACHMENT
, and has MIME type
text/plain
, it's
assumed to be an in-line message and is printed on
System.out
. Otherwise, it's assumed
to be an attachment and is saved into an appropriate file. If necessary, the static
File.createTempFile()
method generates a reasonable name for the file.
Example 7-5. A mail client that handles multipart messages with attached files
import
java.util.*
;
import
java.io.*
;
import
javax.mail.*
;
public
class
AllPartsClient
{
public
static
void
main
(
String
[]
args
)
{
if
(
args
.
length
==
0
)
{
System
.
err
.
println
(
"Usage: java AllPartsClient protocol://username@host:port/foldername"
);
return
;
}
URLName
server
=
new
URLName
(
args
[
0
]);
try
{
Session
session
=
Session
.
getInstance
(
new
Properties
(),
new
MailAuthenticator
(
server
.
getUsername
()));
// Connect to the server and open the folder