如何将MimeBodyPart ContentType设置为“text/html”?

2022-09-01 07:08:00

下面的程序显示了 HTML 多部分 MIME 类型的意外返回值。为什么这个程序打印而不是?text/plaintext/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());
  }
}

我已经尝试了许多替代方法,包括将包装在中,但无济于事。当我尝试使用 a 而不是 .ByteArrayDataSourceDataHandlerMimeMessageMimeBodyPart

要在 Linux 上编译和运行:

javac -classpath .:activation.jar:mail.jar Main.java
java -classpath .:activation.jar:mail.jar Main

答案 1

在封闭的消息上调用 MimeMessage.saveChanges(),这将通过将 MIME 结构级联为对正文部分的调用来更新标头。正是此调用将内容类型从 传输到部件的 MIME 标头。MimeBodyPart.updateHeaders()updateHeadersDataHandlerContent-Type

当您在内部设置的内容时(不明显)JavaMail 会创建一个对象,包装您传入的对象。部件的标头不会立即更新。MimeBodyPartDataHandlerContent-Type

在测试程序中没有直接的方法可以做到这一点,因为您没有包含并且不是 。MimeMessageMimeBodyPart.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() );
  }
}

答案 2

不知道为什么(方法没有记录),但是通过查看源代码,这行应该这样做:

mime_body_part.setHeader("Content-Type", "text/html");

推荐