如何同时发送带有纯文本和HTML文本的邮件,以便每个邮件阅读器都可以选择适合的格式? [英] 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?

查看:227
本文介绍了如何同时发送带有纯文本和HTML文本的邮件,以便每个邮件阅读器都可以选择适合的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

您将要发送MIME多部分/替代消息.你 构造此类消息的方式基本上与您构造 多段/混合消息,使用构造的MimeMultipart对象 使用新的MimeMultipart("alternative").然后,您插入文本/纯文本 主体部分作为多部分的第一部分,并插入text/html 主体部分作为多部分中的第二部分.你需要 自己构造普通部分和html部分以具有适当的位置 内容.有关此类消息的结构的详细信息,请参阅RFC2046.

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?

推荐答案

这是我自己的代码的一部分:

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);

m是我自己的类的实例.

Where m is an instance of my own class.

这篇关于如何同时发送带有纯文本和HTML文本的邮件,以便每个邮件阅读器都可以选择适合的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆