简体   繁体   English

JavaMail:获取 MimeMessage 的大小

[英]JavaMail: get size of a MimeMessage

I'm trying to get the size of a MimeMessage.我正在尝试获取 MimeMessage 的大小。 The method getSize() simply always returns -1. getSize() 方法总是返回 -1。

This is my code:这是我的代码:

MimeMessage m = new MimeMessage(session);
m.setFrom(new InternetAddress(fromAddress, true));
m.setRecipient(RecipientType.TO, new InternetAddress(toAddress, true));
m.setSubject(subject);

MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(body, "text/html");
Multipart mp = new MimeMultipart();
mp.addBodyPart(bodyPart);
m.setContent(mp);

m.getSize(); // -1 is returned

THIS IS THE ANSWER TO MY QUESTION:这是我的问题的答案:

ByteArrayOutputStream os = new ByteArrayOutputStream();
m.writeTo(os);
int bytes = os.size();

A more efficient solution, but requiring an external library, is the following one:一种更有效的解决方案,但需要外部库,如下所示:

public static long getReliableSize(MimeMessage m) throws IOException, MessagingException {
    try (CountingOutputStream out = new CountingOutputStream(new NullOutputStream())) {
        m.writeTo(out);
        return out.getByteCount();
    }
}

Both CountingOutputStream and NullOutputStream are available in Apache Common IO. CountingOutputStream 和 NullOutputStream 在 Apache Common IO 中都可用。 That solution doesn't require to work with a temporary byte buffer (write, allocate, re-allocate, etc.)该解决方案不需要使用临时字节缓冲区(写入、分配、重新分配等)

try calling mp.getSize() to see what it returns, MIMEMessage calls it on mp only.尝试调用 mp.getSize() 以查看它返回的内容,MIMEMessage 仅在 mp 上调用它。 Also From MIME message API也来自 MIME 消息 API

Return the size of the content of this part in bytes.以字节为单位返回这部分内容的大小。 Return -1 if the size cannot be determined.如果无法确定大小,则返回 -1。

As of now you have not passed any contents to the message,that could be the reason on -1 return value.截至目前,您尚未向消息传递任何内容,这可能是 -1 返回值的原因。

Solution provided with Apache Commons is good, but NullOutputStream() constructor is now deprecated. Apache Commons 提供的解决方案很好,但现在不推荐使用 NullOutputStream() 构造函数。 Use the singleton instead:改用单例:

CountingOutputStream out = new CountingOutputStream(NullOutputStream.NULL_OUTPUT_STREAM);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM