简体   繁体   中英

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();

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

try calling mp.getSize() to see what it returns, MIMEMessage calls it on mp only. Also From MIME message API

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

As of now you have not passed any contents to the message,that could be the reason on -1 return value.

Solution provided with Apache Commons is good, but NullOutputStream() constructor is now deprecated. Use the singleton instead:

CountingOutputStream out = new CountingOutputStream(NullOutputStream.NULL_OUTPUT_STREAM);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM