在封闭消息上调用
MimeMessage.saveChanges(),它将通过将MIME结构级联到对您身体部分的MimeBodyPart.updateHeaders()的调用来更新标题。正是这个updateHeaders调用将内容类型从DataHandler传输到该部件的MIME Content-Type头。
当您设置MimeBodyPart的内容时,JavaMail内部(并不明显)会创建一个环绕传入的对象的DataHandler对象。该部分的Content-Type头不会立即更新。
在测试程序中没有直接的方法,因为您没有包含MimeMessage和MimeBodyPart.updateHeaders()不是公开的。
以下是一个工作示例,说明预期和意外的输出:
public class MailTest {
public static void main( String[] args ) throws Exception {
Session mailSession = Session.getInstance( new Properties() );
Transport transport = mailSession.getTransport();
String text = "Hello, World";
String html = "
" + text + "
";MimeMessage message = new MimeMessage( mailSession );
Multipart multipart = new MimeMultipart( "alternative" );
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText( text, "utf-8" );
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent( html, "text/html; charset=utf-8" );
multipart.addBodyPart( textPart );
multipart.addBodyPart( htmlPart );
message.setContent( multipart );
// Unexpected output.
System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
System.out.println( "HTML Content Type: " + htmlPart.getContentType() );
// Required magic (violates principle of least astonishment).
message.saveChanges();
// Output now correct.
System.out.println( "TEXT = text/plain: " + textPart.isMimeType( "text/plain" ) );
System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
System.out.println( "HTML Content Type: " + htmlPart.getContentType() );
System.out.println( "HTML Data Handler: " + htmlPart.getDataHandler().getContentType() );
}
}