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?

后端 未结 1 1261
难免孤独
难免孤独 2021-02-01 19:43

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 mes

1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-01 20:37

    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.

    0 讨论(0)
提交回复
热议问题