Search code examples
apijakarta-mailattachmentmultipartmime-message

Add attachment to existing message using Javamail API


I am connecting to a IMAP server using javamail API and I try to add an attachment to an existing message.

I found the below two threads, but it doesn't fully help:

Adding attachment to existing MimeMessage
Add attachments to existing eml file

I am trying to accomplish the same thing, but somehow I am missing something because in the end the attachment gets added to the message but the format of the content of the email changes to plain text and I see all the content mixed together as plain text, what is wrong?

The message is being read directly from a IMAP connection and not from a .eml file and it can have already other attachments and/or text/html content.

Code:

MimeMessage newmsg = new MimeMessage((MimeMessage) message);

newmsg.setSubject(new_subj);
newmsg.setFlag(Flags.Flag.SEEN, false);

MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.attachFile("test.txt");

Multipart multipart = (Multipart)message.getContent();
multipart.addBodyPart(messageBodyPart);
newmsg.setContent(multipart);

newmsg.saveChanges();

Folder folder_dest = folder.getFolder("test");
folder_dest.appendMessages(new Message[]{newmsg});

Solution

  • You probably want to change

    Multipart multipart = (Multipart)message.getContent();
    

    to

    Multipart multipart = (Multipart)newmsg.getContent();
    

    But I tried it both ways and it worked for me. Of course, this depends on the original message being a multipart/mixed message.

    Here's the changes I made to the msgshow.java sample program to test it:

    diff -r 381478f33ec5 demo/src/main/java/msgshow.java
    --- a/demo/src/main/java/msgshow.java   Wed Jan 27 17:03:33 2016 -0800
    +++ b/demo/src/main/java/msgshow.java   Mon Apr 11 11:39:36 2016 -0700
    @@ -221,7 +221,16 @@
    
                        try {
                            m = folder.getMessage(msgnum);
    -                       dumpPart(m);
    +                       MimeMessage n = new MimeMessage((MimeMessage)m);
    +                       n.setSubject("new subject");
    +                       n.setFlag(Flags.Flag.SEEN, false);
    +                       MimeBodyPart mbp = new MimeBodyPart();
    +                       mbp.attachFile("test.txt");
    +                       Multipart mp = (Multipart)n.getContent();
    +                       mp.addBodyPart(mbp);
    +                       n.setContent(mp);
    +                       n.saveChanges();
    +                       dumpPart(n);
                        } catch (IndexOutOfBoundsException iex) {
                            System.out.println("Message number out of range");
                        }
    

    Can you reproduce the problem with those changes?