A more efficient solution, but requiring an external library, is as follows:
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 methods are available in Apache Common IO. This solution does not require working with a temporary byte buffer (write, distribution, redistribution, etc.).
source share