How do I send mail with both plain text as well as HTML text so that each mail reader can choose the format appropriate for it?

不羁岁月 提交于 2019-12-31 09:30:04

问题


From http://www.oracle.com/technetwork/java/faq-135477.html#sendmpa:

You'll want to send a MIME multipart/alternative message. You construct such a message essentially the same way you construct a multipart/mixed message, using a MimeMultipart object constructed using new MimeMultipart("alternative"). You then insert the text/plain body part as the first part in the multpart and insert the text/html body part as the second part in the multipart. You'll need to construct the plain and html parts yourself to have appropriate content. See RFC2046 for details of the structure of such a message.

Can someone show me some sample code for this?


回答1:


This is a part of my own code:

        final Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(senderAddress, senderDisplayName));
        msg.addRecipient(Message.RecipientType.TO,
                new InternetAddress(m.getRecipient(), m.getRecipientDisplayName()));
        msg.setSubject(m.getSubject());
        // Unformatted text version
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(m.getText(), "text/plain"); 
        // HTML version
        final MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(m.getHtml(), "text/html");
        // Create the Multipart.  Add BodyParts to it.
        final Multipart mp = new MimeMultipart("alternative");
        mp.addBodyPart(textPart);
        mp.addBodyPart(htmlPart);
        // Set Multipart as the message's content
        msg.setContent(mp);
        LOGGER.log(Level.FINEST, "Sending email {0}", m);
        Transport.send(msg);

Where m is an instance of my own class.



来源:https://stackoverflow.com/questions/6756162/how-do-i-send-mail-with-both-plain-text-as-well-as-html-text-so-that-each-mail-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!