zoukankan      html  css  js  c++  java
  • java mail发送html格式的邮件

    // 获取系统属性
    Properties properties = System.getProperties();

    // 设置邮件服务器
    properties.setProperty("mail.smtp.host", mailHost);

    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.put("mail.smtp.socketFactory.port", "465");
    properties.put("mail.smtp.port", "465");

    //SSLSocketFactory类的端口

    properties.put("mail.smtp.auth", "true");
    // 获取默认session对象
    Session session = Session.getDefaultInstance(properties, new Authenticator() {
    public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(fromMail, password); // 发件人邮件用户名、密码
    }
    });

    // 创建默认的 MimeMessage 对象
    MimeMessage message = new MimeMessage(session);

    // Set From: 头部头字段
    message.setFrom(new InternetAddress(fromMail));

    // Set To: 头部头字段
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));

    // Set Subject: 头部头字段
    message.setSubject(mailTitle);

    // 设置消息体

    BodyPart html = new MimeBodyPart();
    Multipart mainPart = new MimeMultipart();
    // 设置HTML内容
    html.setContent(mailContent, "text/html; charset=utf-8");
    mainPart.addBodyPart(html);
    // 将MiniMultipart对象设置为邮件内容
    message.setContent(mainPart);
    // 发送消息
    Transport.send(message);

    发送普通文本内容的时候可直接message.stContent(contentStr);

    但是如果发送的是带有html标签并且希望阅读邮件的时候能被解析为html页面则需要使用如下代码设置邮件内容

    BodyPart html = new MimeBodyPart();
    Multipart mainPart = new MimeMultipart();
    // 设置HTML内容
    html.setContent(mailContent, "text/html; charset=utf-8");
    mainPart.addBodyPart(html);
    // 将MiniMultipart对象设置为邮件内容
    message.setContent(mainPart);

  • 相关阅读:
    maven scope取值
    HashMap 解析
    MySQL中int(M)和tinyint(M)数值类型中M值的意义
    PyCharm 快捷键
    js 闭包,原型链,作用域链
    阿拉伯数字转中文大写金额JS(JavaScript方法)
    JSch
    Java面试点 -【笔记】
    tomcat Connector配置项 参数优化说明
    QRCanvas 示例使用
  • 原文地址:https://www.cnblogs.com/fanwenhao/p/9283292.html
Copyright © 2011-2022 走看看