未使用 Java Mail API 接收消息正文/内容 [英] Not receiving message body/content using Java Mail API

查看:24
本文介绍了未使用 Java Mail API 接收消息正文/内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下使用带有附件和正文部分(消息部分)的 Java Mail API 发送邮件的代码,但我只收到附件,而不是正文消息.

任何帮助或评论将不胜感激.

public static void sendmail(String to, String from, String url,字符串端口,最终字符串用户名,最终字符串密码,字符串文件名) {Properties props = new Properties();props.put("mail.smtp.auth", "true");props.put("mail.smtp.starttls.enable", "false");props.put("mail.smtp.host", url);props.put("mail.smtp.port", port);会话会话 = Session.getInstance(props,新的 javax.mail.Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {返回新的密码认证(用户名,密码);}});尝试 {Message message = new MimeMessage(session);message.setFrom(new InternetAddress(from));message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));message.setSubject("带有图片的 HTML 邮件");message.setContent("

Hello world

", "text/html");message.setHeader("Content-ID", "");Multipart multipart = new MimeMultipart("related");BodyPart messageBodyPart = new MimeBodyPart();System.out.println("附件为" + 文件名);数据源源 = 新文件数据源(文件名);//messageBodyPart.setHeader("Content-ID",Part.ATTACHMENT);messageBodyPart.setDataHandler(new DataHandler(source));messageBodyPart.setFileName(source.getName());multipart.addBodyPart(messageBodyPart);message.setContent(multipart, Part.INLINE);Transport.send(message);System.out.println("消息发送成功....");} catch (MessagingException e) {System.out.println("::::::发送邮件时出错...."+ e.getMessage());抛出新的运行时异常(e);}}

解决方案

您正在调用 setContent() 两次.只有一个 setContent() 可以工作 - 最后一个.

为了在您的消息中包含多个部分,您需要将内容设置为 MimeMultipart.好吧,您正在这样做 - 但多部分对象不包括应该是消息正文的部分.

如果您想要包含文本和附件的消息,您可以创建一个 MimeMultipart(multipart/mixed,而不是 multipart/related和你一样).

以下是如何构建可能的消息的一些示例:

<小时>

最简单的是带有一些附件的文本.例如,您想将您的简历发送给某人,因此您写了几句话的介绍并附上一个或多个文件(求职信,简历):

<前>mime───多部分/混合─┬─文本├─附件1└─附件2

Multipart/mixed(MimeMultipart 的默认设置)意味着电子邮件代理将按顺序显示各个部分 - 一个接一个.

  • 如果附件的内容处理是 inline,并且电子邮件代理能够显示给定的附件类型,那么它将显示在邮件本身内部 - 在其末尾.
  • 如果附件的 content-disposition 是 attachment,它们通常会显示为某种用于保存附件的图标或链接.
<小时>

如果你想发送一个漂亮的 HTML 消息,习惯上同时包含一个纯文本版本和一个 HTML 版本.这样即使在不支持 HTML 的电子邮件阅读器中,收件人也可以阅读它.如果收件人可能有视力障碍,这将非常有帮助.所以,你需要使用 multipart/alternative:

<前>mime───multipart/mixed─┬─multipart/alternative─┬─text/plain│ └─文本/html├─附件1└─附件2

所以,同样,邮件内容包括三个部分,正文和两个附件.但是正文本身是一个MimeMultipart(alternative),它包含纯文本版本和HTML 版本.请记住首先放置纯文本,然后放置 HTML,因为惯例是邮件代理选择它知道如何显示的最后一个选项.

附件将在正文之后依次显示,就像以前一样.

<小时>

现在让我们看看一封没有附件"的邮件,但它确实有应该嵌入 HTML 中的图像.在这种情况下,邮件代理需要知道附件不仅仅是发送给阅读器以供下载的文件,而且应该与 HTML 相关联地显示它们.所以正确的 MIME 类型是 multipart/related,以表明这些部分是相关的.在这种情况下,您还需要为它们提供正确的内容 ID,并在 HTML 中使用这些内容 ID.这不是 MIME 标准的一部分,但现在 HTML 邮件通常是这样处理的.

就 MIME 而言,这样的消息看起来像:

<前>mime───multipart/alternative─┬─text/plain└─多部分/相关─┬─文本/html├─内嵌图片1└─内嵌图2

这次我们没有附件,所以我们可以把multipart/alternative作为我们的顶级内容.它首先有明文替代,就像以前一样,但第二个替代本身是一个 MimeMultipart("related").

在其中,您有 HTML 部分和两个图像.HTML 及其图像必须始终是同一个多部分/相关对象的一部分.

<小时>

现在,如果您想将您的文档附加到这样的消息(其中包含 HTML 图像)中该怎么办?然后你会使用这样的东西:

<前>mime───multipart/mixed─┬─multipart/alternative─┬─text/plain│ └─多部分/相关─┬─文本/html│ ├─内嵌图片1│ └─内嵌图2├─附件1└─附件2

因此您的顶级对象是多部分/混合的,允许您将附件按顺序添加到您的消息中.消息正文"(multipart/mixed 的第一部分)是 multipart/alternative 的复杂结构,其中嵌入了 multipart/related.然后是其他附件.

<小时>

总结:

  • 如果消息具有任何不只是纯文本正文的结构,则其内容必须是某种MimeMultipart 对象.
  • multipart/mixed 消息的第一部分应该是您的可读消息,其余部分是附件.
  • multipart/alternative 消息给出了相同内容的不同显示替代方案,从最常见的分母到最罕见的呈现类型(例如纯文本→HTML→富文本→专有格式)和收件人的邮件程序选择它知道如何显示的最后一个.
  • multipart/related 消息通常用于将 HTML 正文与其内联消息组合在一起.第一部分是 HTML,其他部分具有 HTML 用于其 <img src="..."/> 标签的 Content-ID.

I have below code for sending mail using Java Mail API with attachment and body part (message part), but I am getting only the attachment, not the body message.

Any help or comments will be appreciated.

public static void sendmail(String to, String from, String url,
        String port, final String username, final String password,
        String filename) {

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "false");
    props.put("mail.smtp.host", url);
    props.put("mail.smtp.port", port);

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));
        message.setSubject("HTML        mail    with    images");
        message.setContent("<h1>Hello    world</h1>", "text/html");
        message.setHeader("Content-ID", "<memememe>");
        Multipart multipart = new MimeMultipart("related");
        BodyPart messageBodyPart = new MimeBodyPart();
        System.out.println("file    attached    is    " + filename);
        DataSource source = new FileDataSource(filename);
        // messageBodyPart.setHeader("Content-ID",Part.ATTACHMENT);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(source.getName());
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart, Part.INLINE);
        Transport.send(message);
        System.out.println("Sent    message    successfully....");
    } catch (MessagingException e) {
        System.out.println("::::::Error    while    sending    mail...."
                + e.getMessage());
        throw new RuntimeException(e);
    }
}

解决方案

You are calling setContent() twice. Only one setContent() will work - the last one.

In order to have more than one part in your message you need to set the content to a MimeMultipart. Well, you are doing that - but the multipart object does not include the part that's supposed to be the message body.

If you want a message that has a text and an attachment, you create a MimeMultipart (multipart/mixed, not multipart/related as you did).

Here are some examples of how to structure possible messages:


The simplest of all is text with a few attachments. For example, you want to send your CV to someone, So you write a few words of introduction and attach one or more document (cover letter, CV):

mime───multipart/mixed─┬─text
                       ├─attachment1
                       └─attachment2

Multipart/mixed (the default for a MimeMultipart) means that the e-mail agent will show the parts serially - one after the other.

  • If the attachments' content-disposition is inline, and the e-mail agent is capable to show the given attachment type, then it will be shown inside the message itself - at its end.
  • If the attachments' content-disposition is attachment, they will usually be shown as some sort of icons or links for saving the attachments.

If you want to send a pretty HTML message, it is customary to include both a plaintext version and an HTML version. This is so that the recipient may be able to read it even in an e-mail reader that doesn't support HTML. It's very helpful if the recipient might be visually-impaired. So, you need to use multipart/alternative:

mime───multipart/mixed─┬─multipart/alternative─┬─text/plain
                       │                       └─text/html
                       ├─attachment1
                       └─attachment2

So, again, the message content includes three parts, the body and the two attachments. But the body itself is a MimeMultipart(alternative), and it contains the plaintext version and the HTML version. Remember to put the plaintext first, and the HTML second, as the convention is for the mail agent to pick the last alternative that it knows how to display.

The attachments are going to be displayed serially after the body, just like before.


Now let's look at a mail that doesn't have "attachments", but it does have images that are supposed to be embedded inside the HTML. In this case, the mail agent needs to know that the attachments are not just files sent over to the reader to be downloaded, but that it should display them in association with the HTML. So the correct mime type for that is multipart/related, to show that the parts are related. In this case, you also need to give them proper content IDs, and use those content IDs in the HTML. This is not part of the MIME standard, but it's how HTML mail is usually done these days.

As far as MIME is concerned, such a message will look like:

mime───multipart/alternative─┬─text/plain
                             └─multipart/related─┬─text/html
                                                 ├─embedded image 1
                                                 └─embedded image 2

This time we don't have attachments, so we can put the multipart/alternative as our top level content. It has the plaintext alternative first, like before, but the second alternative is itself a MimeMultipart("related").

Inside it, you have the HTML part, and the two images. The HTML and its images must always be parts of the same multipart/related object.


Now, what if you wanted to attach your document to such a message, one that has HTML and images inside it? Then you would be using something like this:

mime───multipart/mixed─┬─multipart/alternative─┬─text/plain
                       │                       └─multipart/related─┬─text/html
                       │                                           ├─embedded image 1
                       │                                           └─embedded image 2
                       ├─attachment1
                       └─attachment2

So your top level object is multipart/mixed, allowing you to add attachments serially to your message. The message "body" (the first part of the multipart/mixed) is the complex structure of multipart/alternative with an embedded multipart/related. And then the other attachments follow that.


In summary:

  • If the message has any structure that is more than just a plain text body, then its content has to be a MimeMultipart object of some kind.
  • A multipart/mixed message has a first part which is supposed to be your readable message, and the rest are attachments.
  • A multipart/alternative message gives different display alternatives of the same content, ordered from most common denominator to most rare presentation type (e.g. plain text→HTML→rich text→proprietary formatting) and the recipient's mail program picks the last one that it knows how to display.
  • A multipart/related message is usually used to combine an HTML body with its inline messages. The first part is the HTML, the other parts have Content-IDs that the HTML uses for its <img src="..." /> tags.

这篇关于未使用 Java Mail API 接收消息正文/内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆