谷歌应用程序引擎JAVA:如何在谷歌应用程序引擎上使用java邮件api时发送的邮件中嵌入html?

时间:2011-07-10 12:00:23

标签: java google-app-engine javamail

这是我用来发送邮件的工作代码但如果将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);

3 个答案:

答案 0 :(得分:10)

尝试使用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);

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

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

答案 1 :(得分:1)

检查MimeMessage documentation,您可以setText()重载签名,您可以在其中指定 charset Mime子类型

msg.setText("Your html body", "utf-8", "html");

答案 2 :(得分:1)

您应该使用低级API的MailService.Message和MailService。例如:

Message msg = new Message();
    msg.setSender(_sender);
    msg.setTo(_recipient);
    msg.setSubject(_msgSubject);
    msg.setHtmlBody("<h1 style="height:1200px;">THIS IS RUSSIA!!!</h1>");
    MailService service = MailServiceFactory.getMailService();
    try {
        service.send(msg);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }