Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaMail: get size of a MimeMessage

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();
like image 952
yelo3 Avatar asked May 23 '11 09:05

yelo3


People also ask

What is MimeMessage?

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.

What is MimeMessage spring boot?

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.


1 Answers

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

like image 121
Luc Claes Avatar answered Sep 20 '22 18:09

Luc Claes