gpt4 book ai didi

Java邮件 : get size of a MimeMessage

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:57:17 24 4
gpt4 key购买 nike

我正在尝试获取 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 中可用。该解决方案不需要使用临时字节缓冲区(写入、分配、重新分配等)

关于Java邮件 : get size of a MimeMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6095181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com