JavaMail:获取MimeMessage的大小

问题描述

| 我正在尝试获取MimeMessage的大小。 方法getSize()总是总是返回-1。 这是我的代码
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
这是我的问题的答案:
ByteArrayOutputStream os = new ByteArrayOutputStream();
m.writeto(os);
int bytes = os.size();
    

解决方法

尝试调用mp.getSize()来查看返回的内容,MIMEMessage仅在mp上调用它。 也来自MIME消息API   返回内容的大小   这部分以字节为单位。如果-1,则返回-1   大小无法确定。 截至目前,您尚未将任何内容传递给消息,这可能是返回值-1的原因。     ,以下是一种更有效的解决方案,但需要一个外部库:
public static long getReliableSize(MimeMessage m) throws IOException,MessagingException {
    try (CountingOutputStream out = new CountingOutputStream(new NullOutputStream())) {
        m.writeTo(out);
        return out.getByteCount();
    }
}
Apache Common IO中提供了CountingOutputStream和NullOutputStream。该解决方案不需要使用临时字节缓冲区(写入,分配,重新分配等)。