下面的程序显示了HTML多部分MIME类型的意外返回值。为什么此程序打印text/plain而不打印text/html

public class Main {
  public static void main(String[] args) throws javax.mail.MessagingException, java.io.IOException {
    javax.mail.internet.MimeBodyPart mime_body_part = new javax.mail.internet.MimeBodyPart();
    mime_body_part.setContent("<h1>foo</h1>", "text/html");
    System.out.println(mime_body_part.getContentType());
  }
}
我尝试了许多其他方法,包括设置包裹在ByteArrayDataSource中的DataHandler,但无济于事。当我尝试使用MimeMessage而不是MimeBodyPart时,会发生相同的事情。
要在Linux上编译并运行:
javac -classpath .:activation.jar:mail.jar Main.java
java -classpath .:activation.jar:mail.jar Main

最佳答案

在封闭的消息上调用 MimeMessage.saveChanges() ,它将通过将MIME结构层叠为对 body 部位的MimeBodyPart.updateHeaders()的调用来更新 header 。正是updateHeaders调用将内容类型从DataHandler转移到部件的MIME Content-Type header 。

设置MimeBodyPart的内容时,JavaMail在内部(并且不是很明显)会创建一个DataHandler对象,该对象包装了传入的对象。该部件的Content-Type header 不会立即更新。

在您的测试程序中,没有直接的方法可以执行此操作,因为您没有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() );
  }
}

关于java - 如何将MimeBodyPart ContentType设置为 “text/html”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5028670/

10-11 06:37