消息有内容。内容可以是文本,html,DataHandler或Multipart,并且只能有一个内容。多个零件只有身体零件,但可以有多个零件。像消息一样,BodyParts可以包含已经描述的内容。带有HTML,文本和附件的消息可以按如下所示分层查看:message mainMultipart (content for message, subType="mixed") ->htmlAndTextBodyPart (bodyPart1 for mainMultipart) ->htmlAndTextMultipart (content for htmlAndTextBodyPart, subType="alternative") ->textBodyPart (bodyPart2 for the htmlAndTextMultipart) ->text (content for textBodyPart) ->htmlBodyPart (bodyPart1 for htmlAndTextMultipart) ->html (content for htmlBodyPart) ->fileBodyPart1 (bodyPart2 for the mainMultipart) ->FileDataHandler (content for fileBodyPart1 )以及构建此类消息的代码: // the parent or main part if you will Multipart mainMultipart = new MimeMultipart("mixed"); // this will hold text and html and tells the client there are 2 versions of the message (html and text). presumably text // being the alternative to html Multipart htmlAndTextMultipart = new MimeMultipart("alternative"); // set text MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText(text); htmlAndTextMultipart.addBodyPart(textBodyPart); // set html (set this last per rfc1341 which states last = best) MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(html, "text/html; charset=utf-8"); htmlAndTextMultipart.addBodyPart(htmlBodyPart); // stuff the multipart into a bodypart and add the bodyPart to the mainMultipart MimeBodyPart htmlAndTextBodyPart = new MimeBodyPart(); htmlAndTextBodyPart.setContent(htmlAndTextMultipart); mainMultipart.addBodyPart(htmlAndTextBodyPart); // attach file body parts directly to the mainMultipart MimeBodyPart filePart = new MimeBodyPart(); FileDataSource fds = new FileDataSource("/path/to/some/file.txt"); filePart.setDataHandler(new DataHandler(fds)); filePart.setFileName(fds.getName()); mainMultipart.addBodyPart(filePart); // set message content message.setContent(mainMultipart);