JavaMail: get MimeMessage size

I am trying to get the size of a MimeMessage. The getSize () method 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 AN ANSWER TO MY QUESTION:

 ByteArrayOutputStream os = new ByteArrayOutputStream(); m.writeTo(os); int bytes = os.size(); 
+6
source share
2 answers

try calling mp.getSize () to see what it returns; MIMEMessage only calls it on mp. Also from the MIME Message API

Returns the size of the contents of this part in bytes. Return -1 if size cannot be determined.

At the moment, you did not pass any content to the message, this may be the reason for the return value of -1.

+1
source

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.).

0
source

Source: https://habr.com/ru/post/888803/


All Articles