You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaMail发送HTML邮件至Gmail样式异常 求有效示例

JavaMail发送Gmail兼容HTML邮件示例

核心注意事项(Gmail样式限制)

  • 必须使用内联CSS样式:Gmail完全过滤<style>标签内的样式,不支持外部样式表
  • 布局优先用HTML表格:Gmail对div布局的兼容性极差,表格是最稳妥的布局方式
  • 避免复杂CSS选择器:仅使用元素的style属性定义样式,不要用类选择器、后代选择器等
  • 图片用绝对路径:确保Gmail能访问到图片资源,本地图片需上传至公网服务器
  • 禁用JavaScript:Gmail会直接过滤所有JS代码

完整示例代码

Maven依赖(如果使用Maven)

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

Java发送类

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class GmailHtmlMailSender {

    // 发送HTML邮件核心方法
    public static void sendHtmlMail(String smtpHost, int smtpPort, String username, String password,
                                   String toEmail, String subject, String htmlContent) throws MessagingException {
        // SMTP配置
        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true"); // Gmail强制要求TLS

        // 创建认证会话
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        // 构建邮件消息
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        message.setSubject(subject);

        // 设置HTML内容,指定编码和类型
        message.setContent(htmlContent, "text/html; charset=utf-8");

        // 发送邮件
        Transport.send(message);
    }

    // 构建Gmail兼容的HTML内容
    public static String buildGmailFriendlyHtml() {
        // 采用表格嵌套布局,所有样式内联定义
        return "<!DOCTYPE html>" +
                "<html lang=\"zh-CN\">" +
                "<head>" +
                "<meta charset=\"UTF-8\">" +
                "</head>" +
                "<body style=\"margin: 0; padding: 0; background-color: #f5f5f5;\">" +
                "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"background-color: #f5f5f5;\">" +
                "<tr>" +
                "<td align=\"center\" style=\"padding: 20px 0;\">" +
                "<table width=\"600\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"background: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);\">" +
                "<tr>" +
                "<td style=\"padding: 30px;\">" +
                "<h1 style=\"font-size:24px; color:#333; margin:0 0 20px;\">测试邮件标题</h1>" +
                "<p style=\"font-size:16px; color:#666; line-height:1.6; margin:0 0 20px;\">这是一段测试内容,所有样式均为内联定义,确保Gmail能正常渲染。</p>" +
                "<div style=\"background:#eaf4ff; padding:15px; border-radius:4px;\">" +
                "<p style=\"font-size:14px; color:#2d7ff9; margin:0;\">这是带背景色的提示区域</p>" +
                "</div>" +
                "<table width=\"100%\" border=\"0\" cellpadding=\"10\" cellspacing=\"0\" style=\"margin-top:20px; border-collapse:collapse;\">" +
                "<tr style=\"background:#f8f9fa;\">" +
                "<td style=\"font-size:14px; color:#333; font-weight:bold; border:1px solid #dee2e6;\">列1</td>" +
                "<td style=\"font-size:14px; color:#333; font-weight:bold; border:1px solid #dee2e6;\">列2</td>" +
                "</tr>" +
                "<tr>" +
                "<td style=\"font-size:14px; color:#666; border:1px solid #dee2e6;\">测试内容1</td>" +
                "<td style=\"font-size:14px; color:#666; border:1px solid #dee2e6;\">测试内容2</td>" +
                "</tr>" +
                "</table>" +
                "<a href=\"https://example.com\" style=\"display:inline-block; margin-top:20px; padding:12px 24px; background:#2d7ff9; color:#fff; text-decoration:none; border-radius:4px; font-size:16px;\">点击跳转</a>" +
                "</td>" +
                "</tr>" +
                "</table>" +
                "</td>" +
                "</tr>" +
                "</table>" +
                "</body>" +
                "</html>";
    }

    // 测试入口
    public static void main(String[] args) {
        try {
            // Gmail SMTP配置
            String smtpHost = "smtp.gmail.com";
            int smtpPort = 587;
            String username = "your-gmail-account@gmail.com";
            // 注意:Gmail开启两步验证后需使用应用专用密码,而非原密码
            String password = "your-app-specific-password";
            String toEmail = "recipient@example.com";
            String subject = "Gmail兼容HTML邮件测试";

            String htmlContent = buildGmailFriendlyHtml();
            sendHtmlMail(smtpHost, smtpPort, username, password, toEmail, subject, htmlContent);
            System.out.println("邮件发送成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("邮件发送失败");
        }
    }
}

关键说明

  1. Gmail认证注意:如果你的Gmail账号开启了两步验证,必须使用应用专用密码(在Google账号设置中生成),原密码无法通过SMTP认证。
  2. HTML样式规范:所有样式必须直接写在对应元素的style属性中,不要尝试用<style>标签或者外部CSS文件,Gmail会完全过滤这类样式。
  3. 布局选型:用表格做外层容器和内容布局是目前兼容所有主流邮箱(包括Gmail、Outlook)的最可靠方式,避免使用div、flex等现代布局方式。

内容的提问来源于stack exchange,提问作者octtag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 11:12:03