草庐IT

java - 谷歌应用引擎 JAVA : how to embed html in mail being sent while using java mail api on google app engine?

coder 2024-03-27 原文

这是我用来发送邮件的工作代码,但如果我将 html 内容包含到 setText() 方法的字符串参数中,那么它仅作为字符串显示给用户,没有 HTML 效果。

        Message msg = new MimeMessage(session1);
        msg.setFrom(new InternetAddress("abc@xyz.com", "Team Application"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, "Dear "+name1+"."));
        msg.setSubject("Registration confirmation mail");
        msg.setText("Dear "+name1+",\nThanks for registering with us.");
        Transport.send(msg);

最佳答案

尝试使用 setContent 而不是 setText
所以对于您的代码示例:

    Message msg = new MimeMessage(session1);
    msg.setFrom(new InternetAddress("abc@xyz.com", "Team Application"));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, "Dear "+name1+"."));
    msg.setSubject("Registration confirmation mail");
    msg.setContent("Dear <i>"+name1+"</i>,<br>Thanks for registering with us.", "text/html");
    Transport.send(msg);

就个人而言,为此目的,我使用带有文本和 html 版本的多部分消息。这是我自己的代码的一部分:

        // Unformatted text version
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText("plain content");
        // HTML version
        final MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent("<b>html content</b>", "text/html");
        // Create the Multipart.  Add BodyParts to it.
        final Multipart mp = new MimeMultipart();
        mp.addBodyPart(textPart);
        mp.addBodyPart(htmlPart);
        // Set Multipart as the message's content
        msg.setContent(mp);

关于java - 谷歌应用引擎 JAVA : how to embed html in mail being sent while using java mail api on google app engine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6640965/

有关java - 谷歌应用引擎 JAVA : how to embed html in mail being sent while using java mail api on google app engine?的更多相关文章

随机推荐