【问题标题】:Setting Content-Type for MimeMessage?为 MimeMessage 设置内容类型?
【发布时间】:2012-10-19 14:12:12
【问题描述】:

我对 mime 消息的内容类型有一个困惑。假设我有一条 mime 消息。这是一个多部分的消息,正文部分是这样的

  1. Mime 正文部分包含纯文本、html 文本(如 正文粗体)
  2. 包含附件的第二个 mime 正文部分,
  3. 第三个 mime 正文部分包含一个内联图像(从带有 cid 的正文引用)

当我创建正文部分时,我是否应该明确设置顶部 mime 消息的内容类型,然后是每个正文部分?

如果是,在上面的例子中它们应该是什么?

multipart/alternative 建议用于 html,multipart/mixed 建议用于附件,multipart/related 建议用于内联。我都在使用它们,那么完整消息和不同正文部分的 content-Type 应该是什么?

只是为了提供信息,我试图复制上述场景,我既没有为整个 MimeMessage 也没有为正文部分设置内容类型。

但我仍然得到了预期的东西,比如纯文本、正文中的粗体字母、附件、james 上的内联图像在正确的位置

James 为何在不设置内容类型的情况下解释 mime 消息和正文部分,又如何以正确的方式显示它们?

参考代码

  MimeMessage   msg = new MimeMessage(mailSession);
  MimeMultipart mpart = new MimeMultipart();
  MimeBodyPart bp = new MimeBodyPart();
  bp.setText("plain text and html text like<b>Test</>", CHARSET_UTF_8, MESSAGE_HTML_CONTENT_TYPE);
  // add message body
  mpart.addBodyPart(bp);

 // adding attachment
  MimeBodyPart bodyPart = new MimeBodyPart();
  bodyPart.setFileName("WordFile1");
  file = new File("word file");
  DataSource source = new FileDataSource(file);
  bodyPart.setDataHandler(new DataHandler(source));
  mpart.addBodyPart(bodyPart);


 // adding image inline
  MimeBodyPart bodyPart2 = new MimeBodyPart();
  bodyPart2.setFileName("inline image");
  file2 = new File("image1");
  DataSource source2 = new FileDataSource(file);
  bodyPart2.setDataHandler(new DataHandler(source));
  bodyPart2.setDisposition(MimeBodyPart.INLINE);
  bodyPart2.setHeader("Content-ID", "Unique-CntentId");
  bodyPart2.setHeader("Content-Type", "image/jpeg");
  mpart.addBodyPart(bodyPart2);

  // At last setting multipart In MimeMessage
  msg.setContent(mpart);

通过上面的代码,我在与 James 集成的 ThunderBird 中的正确位置获得了正确的 html 文本、纯文本、内联图像和附件。

所以我不明白何时何地将multipart/mixedmultipart/alternativemultipart/related 设置为 Content-Type 还是邮件服务器内部设置的?

【问题讨论】:

    标签: java jakarta-mail mime-types mime-message


    【解决方案1】:

    如果我理解你想要做什么,你想要一个具有这种结构的消息:

      multipart/mixed
        multipart/alternative
          text/plain - a plain text version of the main message body
          multipart/related
            text/html - the html version of the main message body
            image/jpeg - an image referenced by the main body
        application/octet-stream (or whatever) - the attachment
    

    这意味着三个嵌套的多部分。除了默认的“混合”之外,您需要为每个多部分指定子类型。

    多部分/混合和多部分/替代部分相对简单。多部分/相关部分更复杂,您可能需要阅读 RFC 2387 和/或查找其他一些教程来帮助您。

    您可以通过去掉 multipart/related 并让 html 文本引用 Internet 上某处的图像来简化结构。

    您还应该测试具有这种结构的邮件是否会被您关心的所有邮件阅读器正确显示。有些邮件阅读器会比其他结构复杂的邮件阅读器做得更好。

    【讨论】:

    • 谢谢比尔。这正是我在使用 Thunderbird 通过 james 服务器发送邮件时通过调试发现的
    • Bill 如果您有任何想法,您能否在stackoverflow.com/questions/13157171/… 上提供您的想法。提前致谢
    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2011-08-12
    • 2021-10-21
    • 2010-12-27
    • 2012-12-29
    • 2013-03-15
    • 2016-09-28
    • 1970-01-01
    相关资源
    最近更新 更多