在封闭的消息上调用 MimeMessage.saveChanges(
),这将通过将 MIME 结构级联为对正文部分的调用来更新标头。正是此调用将内容类型从 传输到部件的 MIME 标头。MimeBodyPart.updateHeaders()
updateHeaders
DataHandler
Content-Type
当您在内部设置的内容时(不明显)JavaMail 会创建一个对象,包装您传入的对象。部件的标头不会立即更新。MimeBodyPart
DataHandler
Content-Type
在测试程序中没有直接的方法可以做到这一点,因为您没有包含并且不是 。MimeMessage
MimeBodyPart.updateHeaders()
public
下面是一个阐明预期和意外输出的工作示例:
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 = "<h1>" + text + "</h1>";
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() );
}
}