Java Reference
In-Depth Information
try
{
String
fileName
=
p
.
getFileName
();
String
disposition
=
p
.
getDisposition
();
String
contentType
=
p
.
getContentType
();
if
(
contentType
.
toLowerCase
().
startsWith
(
"multipart/"
))
{
processMultipart
((
Multipart
)
p
.
getContent
());
}
else
if
(
fileName
==
null
&&
(
Part
.
ATTACHMENT
.
equalsIgnoreCase
(
disposition
)
||
!
contentType
.
equalsIgnoreCase
(
"text/plain"
)))
{
// pick a random file name.
fileName
=
File
.
createTempFile
(
"attachment"
,
".txt"
).
getName
();
}
if
(
fileName
==
null
)
{
// likely inline
p
.
writeTo
(
System
.
out
);
}
else
{
File
f
=
new
File
(
fileName
);
// find a file that does not yet exist
for
(
int
i
=
1
;
f
.
exists
();
i
++)
{
String
newName
=
fileName
+
" "
+
i
;
f
=
new
File
(
newName
);
}
try
(
OutputStream
out
=
new
BufferedOutputStream
(
new
FileOutputStream
(
f
));
InputStream
in
=
new
BufferedInputStream
(
p
.
getInputStream
()))
{
// We can't just use p.writeTo() here because it doesn't
// decode the attachment. Instead we copy the input stream
// onto the output stream which does automatically decode
// Base-64, quoted printable, and a variety of other formats.
int
b
;
while
((
b
=
in
.
read
())
!=
-
1
)
out
.
write
(
b
);
out
.
flush
();
}
}
}
catch
(
IOException
|
MessagingException
ex
)
{
ex
.
printStackTrace
();
}
}
}
You can also get a part from a multipart message by passing an
OutputStream
to the
part's
writeTo()
method:
public
abstract
void
writeTo
(
OutputStream
out
)
throws
IOException
,
MessagingException
However, this differs from the approach taken in
Example 7-4
in that it does not decode
the part before writing it. It leaves whatever Base64, quoted-printable, or other encoding
the sender applied to the attachment alone. Instead, it simply writes the raw data.