I am working on a project where I need to convert a javax.mail.Message to .eml format and then further convert it into bytes. The current implementation I have is as follows:

ByteArrayOutputStream out = new ByteArrayOutputStream();
msg.writeTo(out);
And for converting to bytes:

byte[] bytes = IOUtils.toByteArray(inputStream);
However, I've noticed that both of these conversion steps are taking a significant amount of time. Is there a more efficient way to perform these conversions, or are there any optimizations that can be applied to speed up this process?

I'd appreciate any insights, suggestions, or best practices for improving the performance of this operation.

The execution of the msg.writeTo(out) method is observed to take approximately 5 minutes when handling file sizes within the range of 4 to 5 MB.
And the input stream is obtained as follows: MimeBodyPart part = (MimeBodyPart) mimeMultipart.getBodyPart(partCount); InputStream inputStream = part.getInputStream(); byte[] bytes = IOUtils.toByteArray(inputStream); for this, it takes 5–6 minutes.