I am writing a mail service based on the JakartaMail Java library. There is a need to receive the contents of the message. To do this, I use msg.getContent(), which returns the Object type. Having studied the issue in detail, I came to the conclusion that there is no universal way to disassemble the content of the message. You can only check for belonging to one of the types. Therefore, it would be advantageous for me to serialize the Object type, which returns the getContent method completely, the problem is that it is not serializable. I will be grateful for your help
blic Blob mapDtoToEntity(Message msg) throws Exception {
Blob blob = new Blob();
Object object = msg.getContent(); // получаем содержимое сообщения
// создаем два потока baos - базовый класс для реализации выходного потока,
// в котором данные записываются в массив байтов
// ois - преобразует объекты в байты
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream ois = new ObjectOutputStream(baos)) {
ois.writeObject(object);
byte[] arrayByteObject = baos.toByteArray();
blob.setObject(arrayByteObject);
}
baos.close(); //закрываем поток
return blob;
}}
Caused by: java.io.NotSerializableException: jakarta.mail.internet.MimeMultipart
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1197)
at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:354)
at com.axsoft.mail.utils.impl.BlobMappingUtils.mapDtoToEntity(BlobMappingUtils.java:26)
at com.axsoft.mail.services.Service.saveMessageRepos(Service.java:51)
at com.axsoft.mail.MailApplication.run(MailApplication.java:26)
a org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:767)
Class MimeMessage
has method writeTo(OutputStream)
which lets you write out the entire message, including its headers. It has a constructor MimeMessage(Session, InputStream)
that lets you create a message from a previously serialized message.
If you don't want to save the entire message but only its body, you can use getDataHandler().writeTo(outputStream)
instead.