I'm trying to get the size of a MimeMessage. The method getSize() simply always returns -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();
MimeMessage uses the InternetHeaders class to parse and store the top level RFC 822 headers of a message. The mail. mime. address. strict session property controls the parsing of address headers.
It supports JavaMail MimeMessages and Spring SimpleMailMessages. SimpleMailMessage class: It is used to create a simple mail message including from, to, cc, subject and text messages. MimeMessagePreparator interface: It is the callback interface for the preparation of JavaMail MIME messages.
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. That solution doesn't require to work with a temporary byte buffer (write, allocate, re-allocate, etc.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With