簡體   English   中英

JavaMail:獲取 MimeMessage 的大小

[英]JavaMail: get size of a 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();

一種更有效的解決方案,但需要外部庫,如下所示:

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

CountingOutputStream 和 NullOutputStream 在 Apache Common IO 中都可用。 該解決方案不需要使用臨時字節緩沖區(寫入、分配、重新分配等)

嘗試調用 mp.getSize() 以查看它返回的內容,MIMEMessage 僅在 mp 上調用它。 也來自 MIME 消息 API

以字節為單位返回這部分內容的大小。 如果無法確定大小,則返回 -1。

截至目前,您尚未向消息傳遞任何內容,這可能是 -1 返回值的原因。

Apache Commons 提供的解決方案很好,但現在不推薦使用 NullOutputStream() 構造函數。 改用單例:

CountingOutputStream out = new CountingOutputStream(NullOutputStream.NULL_OUTPUT_STREAM);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM