-->

Adding attachment to existing MimeMessage

2019-08-10 06:31发布

问题:

I am reading a Mime message like this:

             InputStream is = new FileInputStream("c:\\Temp\\test.eml");
             MimeMessage message = new MimeMessage(session,is);

Now i need to simply add an attachment to the existing MimeMessage without changing anything else.

How can i do this?

I tried:

        messageBodyPart = new MimeBodyPart();

             DataSource source = new FileDataSource("C:\\attachment.pdf");
             messageBodyPart.setDataHandler(new DataHandler(source));
             messageBodyPart.setFileName("encrypted_body.pdf");
             multipart.addBodyPart(messageBodyPart);

             // Send the complete message parts
             message.setContent(multipart);

But it seems to change the original message.

回答1:

So, the answer in this case will be to create a new Message with the content of the old message like this: Multipart multipart = (Multipart)message.getContent();

And then add the attachment to the new message.