Use Multipart/Related for Rich Messages
To ensure that they can be read as easily
as possible, richly formatted messages should be completely
self-contained, instead of relying on images or resources available
on a server. The MIME standard provides another special multipart
type: “related”. Related parts can
refer to each other via URIs pointing to the
Content-ID, or
“CID,” associated with each part. A
CID URI takes the form
“cid:contentid”. You can use the
setHeader( )
method of
MimeBodyPart
to create known content IDs for each message part. Once this is done,
HTML parts can, for example, display an image by referring to the
message part containing the image data.
The following example contains an HTML part that includes an
<img>
tag pointing to the
"cid:myimage" URI. It also contains a second part
containing a GIF image with a content ID of
"myimage".
. . . Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("images@company.com")); msg.setRecipient(Message.RecipientType.TO, new InternetAddress("bob.cratchett@company.com")); msg.setSubject("Image Email"); Multipart multipartRelated = new MimeMultipart("related"); MimeBodyPart mbp = new MimeBodyPart( ); mbp.setContent( "<html><body><img src=\"cid:myimage\"></body></html>", "text/html"); multipartRelated.addBodyPart(mbp); . . . MimeBodyPart mbp2 = new MimeBodyPart( ); mbp2.setDataHandler(new DataHandler(new FileDataSource("c:\\inline.gif"))); mbp2.setFileName("inline.gif"); mbp2.setHeader("Content-ID","myimage"); ...