简体   繁体   中英

Reply to a multipart email message

I would like to add text to the beginning of the email and send it back.

If the letter is MIME "text/plain", it works. If MIME "multipart/*" is not working properly. The sender receives a response with attachment, not with the original body.

How to add text to the "multipart/*" email and send it to the sender?

void replyMessage(String from, int MessageNumber, String MessageText) throws Exception {

    if (messages[MessageNumber].isMimeType("text/plain")) {

        // it work!
        Message msgReply = messages[MessageNumber].reply(false);
        String originalText = messages[MessageNumber].getContent().toString().replaceAll("(?m)^", "> ");

        msgReply.setFrom(new InternetAddress(from));
        msgReply.setText(MessageText + "\n\n---------------\n\n" + originalText);

        Transport.send(msgReply, user, pass);


    } else if (messages[MessageNumber].isMimeType("multipart/*")) {

        // not work!
        MimeMessage msgReply = (MimeMessage) messages[MessageNumber].reply(false);
        msgReply.setFrom(new InternetAddress(from));

        // Create your new message part
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setText("Oiginal message:\n\n");

        // Create and fill part for the forwarded content
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2.setDataHandler(messages[MessageNumber].getDataHandler());

        // Create a multi-part to combine the parts
        Multipart multipart = new MimeMultipart();

        // Add parts to multi part
        multipart.addBodyPart(messageBodyPart1);
        multipart.addBodyPart(messageBodyPart2);

        // add the Multipart to the message
        msgReply.setContent(multipart);

        Transport.send(msgReply, user, pass);
    }
}

You need to combine the original text and the reply text into a single string and a single body part, just like you did in the text/plain case. But then you need to decide what to do with the other parts in the original message. If they're attachments, do you want to discard them? If the original message was multipart/alternative, do you want to update both the text/html and text/plain parts in the reply? If the original was multipart/related, do you want to keep the images and update the text/html in the reply? There's lots more cases you need to consider, and this is even ignoring signed or encrypted messages.

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