精华内容
下载资源
问答
  • java发送html模板的高逼格邮件

    千次阅读 2019-06-25 15:11:04
    java发送html模板的高逼格邮件

    最近做了一个监测k8s服务pod水平伸缩发送邮件的功能(当pod的cpu/内存达到指定阈值后会水平扩展出多个pod、或者指定时间内pod数应扩展到指定数量),一开始写了个格式很low的邮件,像下面这样:

    在这里插入图片描述

    主流程打通,算个v1版本吧,程序员是个追求完美的人,再说这么低逼格的邮件,给客户看,客户也会不满意。那怎么提高邮件的逼格呢?下面写了个简单的demo,v2版本如下:
    在这里插入图片描述

    感兴趣的小伙伴可以参考,模板可以找你公司前端和美工小姐姐设计。

    因为监测k8s服务pod水平伸缩是用go开发的,发送通知邮件提供了个接口,用springboot写的,以下也用springboot做demo

    Springboot的pom.xml文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example</groupId>
        <artifactId>email-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>email-demo</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-lang3</artifactId>
                <version>3.8.1</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.47</version>
            </dependency>
           <!--发送邮件的必要依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-mail</artifactId>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    pod-scale-alarm.html模板文件:
    模板中的{0}、{1}这样的占位符后面java代码会替换掉

    <body style="color: #666; font-size: 14px; font-family: 'Open Sans',Helvetica,Arial,sans-serif;">
    <div class="box-content" style="width: 80%; margin: 20px auto; max-width: 800px; min-width: 600px;">
        <div class="header-tip" style="font-size: 12px;
                                       color: #aaa;
                                       text-align: right;
                                       padding-right: 25px;
                                       padding-bottom: 10px;">
            Confidential - Scale Alarm Use Only
        </div>
        <div class="info-top" style="padding: 15px 25px;
                                     border-top-left-radius: 10px;
                                     border-top-right-radius: 10px;
                                     background: {0};
                                     color: #fff;
                                     overflow: hidden;
                                     line-height: 32px;">
            <img src="cid:icon-alarm" style="float: left; margin: 0 10px 0 0; width: 32px;" /><div style="color:#010e07"><strong>服务实例水平伸缩通知</strong></div>
        </div>
        <div class="info-wrap" style="border-bottom-left-radius: 10px;
                                      border-bottom-right-radius: 10px;
                                      border:1px solid #ddd;
                                      overflow: hidden;
                                      padding: 15px 15px 20px;">
            <div class="tips" style="padding:15px;">
                <p style=" list-style: 160%; margin: 10px 0;">Hi,</p>
                <p style=" list-style: 160%; margin: 10px 0;">{1}</p>
            </div>
            <div class="time" style="text-align: right; color: #999; padding: 0 15px 15px;">{2}</div>
            <br>
            <table class="list" style="width: 100%; border-collapse: collapse; border-top:1px solid #eee; font-size:12px;">
                <thead>
                <tr style=" background: #fafafa; color: #333; border-bottom: 1px solid #eee;">
                    {3}
                </tr>
                </thead>
                <tbody>
                {4}
                </tbody>
            </table>
        </div>
    </div>
    </body>
    

    success-alarm.png图标:
    在这里插入图片描述
    java代码如下,简单的demo,优化可以自己在项目中去做。

    package com.example.emaildemo;
    
    import org.apache.commons.lang3.time.DateFormatUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.mail.javamail.JavaMailSenderImpl;
    import org.springframework.mail.javamail.MimeMessageHelper;
    
    import javax.mail.MessagingException;
    import javax.mail.internet.MimeMessage;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.text.MessageFormat;
    import java.util.Date;
    import java.util.Objects;
    import java.util.Properties;
    
    /**
     * @program: email-demo
     * @description:
     * @author: smallsoup
     * @create: 2019-01-27 16:44
     **/
    
    public class SendEmailUtil {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(SendEmailUtil.class);
    
        public static void main(String[] args) throws MessagingException, IOException {
    
            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
            javaMailSender.setUsername("你的邮箱地址");
            javaMailSender.setPassword("你的邮箱AUTH密码,不是登陆密码哦,在邮箱的设置里单独开启和设置");
            javaMailSender.setHost("smtp.exmail.qq.com");
            javaMailSender.setPort(587);
            javaMailSender.setDefaultEncoding("UTF-8");
            Properties props = new Properties();
            props.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.connectiontimeout", "20000");
            props.setProperty("mail.smtp.timeout", "20000");
            javaMailSender.setJavaMailProperties(props);
    
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setTo(new String[]{"收件人邮箱"});
            helper.setCc("抄送人邮箱");
            helper.setFrom("你的邮箱地址");
            helper.setSubject("liang subject");
            helper.setText(buildContent(), true);
    
    
            String alarmIconName = "success-alarm.png";
            ClassPathResource img = new ClassPathResource(alarmIconName);
            if (Objects.nonNull(img)) {
                helper.addInline("icon-alarm", img);
            }
            javaMailSender.send(message);
        }
    
        private static String buildContent() throws IOException {
    
            //加载邮件html模板
            String fileName = "pod-scale-alarm.html";
            InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName);
            BufferedReader fileReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            try {
                while ((line = fileReader.readLine()) != null) {
                    buffer.append(line);
                }
            } catch (Exception e) {
                LOGGER.error("读取文件失败,fileName:{}", fileName, e);
            } finally {
                inputStream.close();
                fileReader.close();
            }
    
    
            String contentText = "以下是服务实例伸缩信息, 敬请查看.<br>below is the information of service instance scale, please check. ";
            //邮件表格header
            String header = "<td>分区(Namespace)</td><td>服务(Service)</td><td>伸缩结果(Scale Result)</td><td>伸缩原因(Scale Reason)</td><td>当前实例数(Pod instance number)</td>";
            StringBuilder linesBuffer = new StringBuilder();
            linesBuffer.append("<tr><td>" + "myNamespace" + "</td><td>" + "myServiceName" + "</td><td>" + "myscaleResult" + "</td>" +
                    "<td>" + "mReason" + "</td><td>" + "my4" + "</td></tr>");
    
            //绿色
            String emailHeadColor = "#10fa81";
            String date = DateFormatUtils.format(new Date(), "yyyy/MM/dd HH:mm:ss");
            //填充html模板中的五个参数
            String htmlText = MessageFormat.format(buffer.toString(), emailHeadColor, contentText, date, header, linesBuffer.toString());
    
            //改变表格样式
            htmlText = htmlText.replaceAll("<td>", "<td style=\"padding:6px 10px; line-height: 150%;\">");
            htmlText = htmlText.replaceAll("<tr>", "<tr style=\"border-bottom: 1px solid #eee; color:#666;\">");
            return htmlText;
        }
    }
    


    作者简洁

    作者:小碗汤,一位热爱、认真写作的小伙,目前维护原创公众号:『我的小碗汤』,专注于写golang、docker、kubernetes等知识等提升硬实力的文章,期待你的关注。 转载说明:务必注明来源(注明:来源于公众号:我的小碗汤, 作者:小碗汤)

    展开全文
  • 1、实测,代码是可运行的! 2、根据html模板,替换其中的内容 实现定制化发送邮件。 3、内附readme.txt,有详细说明。
  • Java发送邮件,优美html邮件模板分享

    千次阅读 2019-09-24 12:47:27
    以前有用JavaMail写过发送html邮件,当时在benchmark网站自己设计了个html模板,分享记录一下。 预览: 访客端 以上模板的html文件下载 下载点这里 云盘密码: emailpw1 站长端 以上模板的html...

    以前有用JavaMail写过发送html邮件,当时在benchmark自己设计了个html模板,分享记录一下。

        • 2020-12-03 更新

    最近做了一个email通知功能,又优化设计了一下之前的邮件通知模板。
    效果如下:
    在这里插入图片描述
    以上模板的html文件下载
    https://gitee.com/bhy702/email-template.html

    以上html邮件模板对应的html邮件发送代码可参考springboot多线程异步发送email,html模板渲染


        • 原文

    以下模板的邮件通知演示地址:点这里 点击联系我,留言后,会接收到访客留言反馈邮件。

    预览:

    访客反馈端

    在这里插入图片描述
    以上模板的html文件下载
    下载点这里
    云盘密码: emailpw1


    留言通知端

    在这里插入图片描述
    以上模板的html文件下载
    下载点这里
    密码: emailpw2


    • 2020-12-03 建议使用springboot+thymeleaf完成模板的变量数据填充,完善代码可参考上面最新的html邮件发送代码链接。

    Java实现发送html邮件可参考博客SpringBoot使用JavaMailSender实现发送邮件功能【注意】 需要将博客中邮件发送方法sendSimpleMail改为以下sendHtmlMail方法实现即可。

    	// 发送html格式邮件
        public static JsonResult sendHtmlMail(JavaMailSender javaMailSender,String email, String subject, String content) {
    
            MimeMessage message = javaMailSender.createMimeMessage();
            try {
                //true表示需要创建一个multipart message
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom("xxx"+"<"+"xxxxxxx@qq.com"+">");
                helper.setTo(email);
                helper.setSubject(subject);
                helper.setText(content, true);
    
                javaMailSender.send(message);
            } catch (MessagingException e) {
                e.printStackTrace();
                return JsonResult.error("哎呀~邮件服务器抽风了");
            } catch (MailAuthenticationException e) {
                e.printStackTrace();
                return JsonResult.error("哎呀~邮件服务器抽风了");
            } catch (Exception e) {
                e.printStackTrace();
                return JsonResult.error("邮件发送失败");
            }
            return JsonResult.success("邮件发送成功");
        }
    

    欢迎访问本文的个人博客链接: https://br-bai.github.io/2019/09/24/Java发送邮件,html邮件模板分享/

    展开全文
  • Java 如何发送邮件模板 首先得引入发送邮件模板

    Java 如何发送邮件模板,第一次开发邮件,用了两个多小时,希望看过这个文章的,可以在十分钟内完成。

    第一步,添加maven 依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>

    第二步:新建邮件工具类,代码如下;

    注意:工具类由业务Controller或者Service调用,里面有单发、群发邮件,buildContent 是读取HTML并传入参数的接口;

    package com.hicling.puhua.common.utils;
    
    import java.io.*;
    import java.text.MessageFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Properties;
    import javax.mail.Message;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.context.annotation.ComponentScan;
    
    /**
     * 发送邮件工具类
     */
    @ComponentScan
    public class MailUtil {
    
        private final static Logger logger = LoggerFactory.getLogger(MailUtil.class);
    
        public static String buildContent(HashMap<String,String> parameterMap) throws IOException {
            String reminderDate = parameterMap.get("reminderDate");
            //加载邮件html模板
            File fileName = new File("Email_Template_30.html");
            BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
    
            StringBuffer buffer = new StringBuffer();
            String line = "";
            try {
                while ((line = fileReader.readLine()) != null) {
                    buffer.append(line);
                }
            } catch (Exception e) {
                logger.error("读取文件失败,fileName:{}", fileName, e);
            } finally {
                fileReader.close();
            }
    
            Date date = new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String array[] = {"梅奥心磁","100",sdf.format(date),"serverId"};
    
            //替换参数
            String htmlText = MessageFormat.format(buffer.toString(), array);
            return htmlText;
        }
    
        /**
         * 邮件发送
         * @param mailHost 邮件服务地址
         * @param fromMail 发件人
         * @param fromName 发件人名
         * @param fromMailPwd 发件人密码
         * @param toMails 收件人,多个用英文逗号分隔
         * @param mailTitle 邮件标题
         * @param mailContent 邮件内容
         * @throws Exception
         */
        public static void sendMail(String mailHost, String fromMail, String fromName, String fromMailPwd,
                                    String toMails, String mailTitle, String mailContent) throws Exception {
            String[] toMailArr = null;
            if (toMails != null && !toMails.equals("")) {
                toMailArr = toMails.split(",");
            } else {
                throw new Exception("邮件发送人不能为空");
            }
    
            // 邮件属性信息
            Properties props = new Properties();
            props.put("mail.host", mailHost);
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.auth", "true");
    
            Session session = Session.getInstance(props); // 根据属性新建一个邮件会话
            //session.setDebug(true); // 是否打印调试信息
            toMailArr = toMails.split(",");
            for (String to : toMailArr) {
                MimeMessage message = new MimeMessage(session); // 由邮件会话新建一个消息对象
                message.setFrom(new InternetAddress(fromMail));// 设置发件人的地址
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(to, fromName));// 设置收件人,并设置其接收类型为TO
                message.setSubject(mailTitle);// 设置标题
                message.setContent(mailContent, "text/html;charset=UTF-8"); // 设置邮件内容类型为html
                message.setSentDate(new Date());// 设置发信时间
                message.saveChanges();// 存储邮件信息
    
                // 发送邮件
                Transport transport = session.getTransport();
                transport.connect(fromMail, fromMailPwd);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            }
        }
    
        /**
         * 邮件发送(群发)
         * @param mailHost 邮件服务地址
         * @param fromMail 发件人
         * @param fromName 发件人名
         * @param fromMailPwd 发件人密码
         * @param toMails 收件人,多个用英文逗号分隔
         * @param mailTitle 邮件标题
         * @param mailContent 邮件内容
         * @throws Exception
         */
        public static void sendGroupMail(String mailHost, String fromMail, String fromName, String fromMailPwd,
                                         String toMails, String mailTitle, String mailContent) throws Exception {
            String[] toMailArr = null;
            if (toMails != null && !toMails.equals("")) {
                toMailArr = toMails.split(",");
            } else {
                throw new Exception("邮件发送人不能为空");
            }
    
            // 邮件属性信息
            Properties props = new Properties();
            props.put("mail.host", mailHost);
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.auth", "true");
    
    
            Session session = Session.getInstance(props); // 根据属性新建一个邮件会话
            //session.setDebug(true); // 是否打印调试信息
            MimeMessage message = new MimeMessage(session); // 由邮件会话新建一个消息对象
            message.setFrom(new InternetAddress(fromMail)); // 设置发件人的地址
            InternetAddress[] sendTo = new InternetAddress[toMailArr.length];
            for (int i = 0; i < toMailArr.length; i++) {
                sendTo[i] = new InternetAddress(toMailArr[i], fromName);
            }
            message.setRecipients(Message.RecipientType.TO, sendTo); // 设置收件人,并设置其接收类型为TO
            message.setSubject(mailTitle); // 设置标题
            message.setContent(mailContent, "text/html;charset=UTF-8"); // 设置邮件内容类型为html
            message.setSentDate(new Date()); // 设置发信时间
            message.saveChanges(); // 存储邮件信息
    
            // 发送邮件
            Transport transport = session.getTransport();
            transport.connect(fromMail, fromMailPwd);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }
    
        /**
         * 读取html文件为String
         * @param htmlFileName
         * @return
         * @throws Exception
         */
        public static String readHtmlToString(String htmlFileName) throws Exception{
            InputStream is = null;
            Reader reader = null;
            try {
                is = MailUtil.class.getClassLoader().getResourceAsStream(htmlFileName);
                if (is ==  null) {
                    throw new Exception("未找到模板文件");
                }
                reader = new InputStreamReader(is, "UTF-8");
                StringBuilder sb = new StringBuilder();
                int bufferSize = 1024;
                char[] buffer = new char[bufferSize];
                int length = 0;
                while ((length = reader.read(buffer, 0, bufferSize)) != -1){
                    sb.append(buffer, 0, length);
                }
                return sb.toString();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    logger.error("关闭io流异常", e);
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch ( IOException e) {
                    logger.error("关闭io流异常", e);
                }
            }
        }
    
    }

     

    第三步: 编写模板邮件,一般这边由前端完成HMTL的编写,这边也给个HTML实例,由此展开我在完成模板邮件功能时遇到的坑。

    注意点1(必读): 在需要传入参数的地方使用{index}占位符,如{0}、{1}、{2}、{3};你也可以在一下代码中搜索{0},代码的是客户名称,在后续代码中替换

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office" style="width:100%;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;padding:0;Margin:0">
     <head> 
      <meta charset="UTF-8"> 
      <meta content="width=device-width, initial-scale=1" name="viewport"> 
      <meta name="x-apple-disable-message-reformatting"> 
      <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
      <meta content="telephone=no" name="format-detection"> 
      <title>Reminder : Renew License ETE Platform</title> 
      <!--[if (mso 16)]>
        <style type="text/css">
        a '{'text-decoration: none;'}'
        </style>
        <![endif]-->
      <!--[if gte mso 9]><style>sup '{' font-size: 100% !important; '}'</style><![endif]-->
      <!--[if gte mso 9]>
    <xml>
        <o:OfficeDocumentSettings>
        <o:AllowPNG></o:AllowPNG>
        <o:PixelsPerInch>96</o:PixelsPerInch>
        </o:OfficeDocumentSettings>
    </xml>
    <![endif]-->
      <!--[if !mso]><!-- -->
      <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700,700i" rel="stylesheet">
      <!--<![endif]-->
      <style type="text/css">
    @media only screen and (max-width:600px) '{'p, ul li, ol li, a '{' font-size:16px!important; line-height:150%!important '}' h1 '{' font-size:32px!important; text-align:center; line-height:120%!important '}' h2 '{' font-size:26px!important; text-align:center; line-height:120%!important '}' h3 '{' font-size:20px!important; text-align:center; line-height:120%!important '}' h1 a '{' font-size:32px!important '}' h2 a '{' font-size:26px!important '}' h3 a '{' font-size:20px!important '}' .es-menu td a '{' font-size:16px!important '}' .es-header-body p, .es-header-body ul li, .es-header-body ol li, .es-header-body a '{' font-size:16px!important '}' .es-footer-body p, .es-footer-body ul li, .es-footer-body ol li, .es-footer-body a '{' font-size:16px!important '}' .es-infoblock p, .es-infoblock ul li, .es-infoblock ol li, .es-infoblock a '{' font-size:12px!important '}' *[class="gmail-fix"] '{' display:none!important '}' .es-m-txt-c, .es-m-txt-c h1, .es-m-txt-c h2, .es-m-txt-c h3 '{' text-align:center!important '}' .es-m-txt-r, .es-m-txt-r h1, .es-m-txt-r h2, .es-m-txt-r h3 '{' text-align:right!important '}' .es-m-txt-l, .es-m-txt-l h1, .es-m-txt-l h2, .es-m-txt-l h3 '{' text-align:left!important '}' .es-m-txt-r img, .es-m-txt-c img, .es-m-txt-l img '{' display:inline!important '}' .es-button-border '{' display:inline-block!important '}' a.es-button '{' font-size:16px!important; display:inline-block!important; border-width:15px 30px 15px 30px!important '}' .es-btn-fw '{' border-width:10px 0px!important; text-align:center!important '}' .es-adaptive table, .es-btn-fw, .es-btn-fw-brdr, .es-left, .es-right '{' width:100%!important '}' .es-content table, .es-header table, .es-footer table, .es-content, .es-footer, .es-header '{' width:100%!important; max-width:600px!important '}' .es-adapt-td '{' display:block!important; width:100%!important '}' .adapt-img '{' width:100%!important; height:auto!important '}' .es-m-p0 '{' padding:0px!important '}' .es-m-p0r '{' padding-right:0px!important '}' .es-m-p0l '{' padding-left:0px!important '}' .es-m-p0t '{' padding-top:0px!important '}' .es-m-p0b '{' padding-bottom:0!important '}' .es-m-p20b '{' padding-bottom:20px!important '}' .es-mobile-hidden, .es-hidden '{' display:none!important '}' tr.es-desk-hidden, td.es-desk-hidden, table.es-desk-hidden '{' display:table-row!important; width:auto!important; overflow:visible!important; float:none!important; max-height:inherit!important; line-height:inherit!important '}' .es-desk-menu-hidden '{' display:table-cell!important '}' table.es-table-not-adapt, .esd-block-html table '{' width:auto!important '}' table.es-social '{' display:inline-block!important '}' table.es-social td '{' display:inline-block!important '}' '}'
    #outlook a '{'
       padding:0;
    '}'
    .ExternalClass '{'
       width:100%;
    '}'
    .ExternalClass,
    .ExternalClass p,
    .ExternalClass span,
    .ExternalClass font,
    .ExternalClass td,
    .ExternalClass div '{'
       line-height:100%;
    '}'
    .es-button '{'
       mso-style-priority:100!important;
       text-decoration:none!important;
    '}'
    a[x-apple-data-detectors] '{'
       color:inherit!important;
       text-decoration:none!important;
       font-size:inherit!important;
       font-family:inherit!important;
       font-weight:inherit!important;
       line-height:inherit!important;
    '}'
    .es-desk-hidden '{'
       display:none;
       float:left;
       overflow:hidden;
       width:0;
       max-height:0;
       line-height:0;
       mso-hide:all;
    '}'
    </style> 
     </head> 
     <body style="width:100%;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;padding:0;Margin:0"> 
      <div class="es-wrapper-color" style="background-color:#EEEEEE"> 
       <!--[if gte mso 9]>
             <v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="t">
                <v:fill type="tile" color="#eeeeee"></v:fill>
             </v:background>
          <![endif]--> 
       <table class="es-wrapper" width="100%" cellspacing="0" cellpadding="0" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;padding:0;Margin:0;width:100%;height:100%;background-repeat:repeat;background-position:center top"> 
         <tr style="border-collapse:collapse"> 
          <td valign="top" style="padding:0;Margin:0"> 
           <table class="es-content" cellspacing="0" cellpadding="0" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;table-layout:fixed !important;width:100%"> 
             <tr style="border-collapse:collapse"> 
              <td align="center" style="padding:0;Margin:0"> 
               <table class="es-content-body" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;background-color:transparent;width:600px" cellspacing="0" cellpadding="0" align="center"> 
                 <tr style="border-collapse:collapse"> 
                  <td align="left" style="Margin:0;padding-left:10px;padding-right:10px;padding-top:15px;padding-bottom:15px"> 
                   <!--[if mso]><table style="width:580px" cellpadding="0" cellspacing="0"><tr><td style="width:282px" valign="top"><![endif]--> 
                   <table class="es-left" cellspacing="0" cellpadding="0" align="left" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;float:left"> 
                     <tr style="border-collapse:collapse"> 
                      <td align="left" style="padding:0;Margin:0;width:282px"> 
                       </td> 
                     </tr> 
                   
                   <!--[if mso]></td></tr></table><![endif]--></td> 
                 </tr> 
               </table></td> 
             </tr> 
           </table> 
           <table class="es-content" cellspacing="0" cellpadding="0" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;table-layout:fixed !important;width:100%"> 
             <tr style="border-collapse:collapse"></tr> 
             <tr style="border-collapse:collapse"> 
              <td align="center" style="padding:0;Margin:0"> 
               <table class="es-header-body" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;background-color:#044767;width:600px" cellspacing="0" cellpadding="0" bgcolor="#044767" align="center"> 
                 <tr style="border-collapse:collapse"> 
                  <td align="left" style="Margin:0;padding-top:35px;padding-bottom:35px;padding-left:35px;padding-right:35px"> 
                   <!--[if mso]><table style="width:530px" cellpadding="0" cellspacing="0"><tr><td style="width:340px" valign="top"><![endif]--> 
                   <table class="es-left" cellspacing="0" cellpadding="0" align="left" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;float:left"> 
                     <tr style="border-collapse:collapse"> 
                      <td class="es-m-p0r es-m-p20b" valign="top" align="center" style="padding:0;Margin:0;width:340px"> 
                       <table width="100%" cellspacing="0" cellpadding="0" role="presentation" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> 
                         <tr style="border-collapse:collapse"> 
                          <td class="es-m-txt-c" align="left" style="padding:0;Margin:0"><h1 style="Margin:0;line-height:36px;mso-line-height-rule:exactly;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;font-size:32px;font-style:normal;font-weight:bold;color:#FFFFFF">ETE Health Platform</h1></td> 
                         </tr> 
                       </table></td> 
                     </tr> 
                   </table> 
                   <!--[if mso]></td><td style="width:20px"></td><td style="width:170px" valign="top"><![endif]--> 
                   <table cellspacing="0" cellpadding="0" align="right" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> 
                     <tr class="es-hidden" style="border-collapse:collapse"> 
                      <td class="es-m-p20b" align="left" style="padding:0;Margin:0;width:170px"> 
                       <table width="100%" cellspacing="0" cellpadding="0" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> 
                         <tr style="border-collapse:collapse"> 
                          <td style="padding:0;Margin:0"> 
                           <table cellspacing="0" cellpadding="0" align="right" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> 
                             <tr style="border-collapse:collapse"> 
                              <td align="center" style="padding:0;Margin:0;display:none"></td> 
                             </tr> 
                           </table></td> 
                         </tr> 
                       </table></td> 
                     </tr> 
                   </table> 
                   <!--[if mso]></td></tr></table><![endif]--></td> 
                 </tr> 
               </table></td> 
             </tr> 
           </table> 
           <table class="es-content" cellspacing="0" cellpadding="0" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;table-layout:fixed !important;width:100%"> 
             <tr style="border-collapse:collapse"> 
              <td align="center" style="padding:0;Margin:0"> 
               <table class="es-content-body" cellspacing="0" cellpadding="0" bgcolor="#ffffff" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;background-color:#FFFFFF;width:600px"> 
                 <tr style="border-collapse:collapse"> 
                  <td style="Margin:0;padding-bottom:35px;padding-left:35px;padding-right:35px;padding-top:40px;background-color:#F7F7F7" bgcolor="#f7f7f7" align="left"> 
                   <table width="100%" cellspacing="0" cellpadding="0" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> 
                     <tr style="border-collapse:collapse"> 
                      <td valign="top" align="center" style="padding:0;Margin:0;width:530px"> 
                       <table width="100%" cellspacing="0" cellpadding="0" role="presentation" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> 
                         <tr style="border-collapse:collapse"> 
                          <td style="Margin:0;padding-top:20px;padding-bottom:25px;padding-left:35px;padding-right:35px;font-size:0" align="center"><a target="_blank" style="-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;font-size:15px;text-decoration:none;color:#ED8E20"><img src="https://eyetoeyesecurity.info/etelogoblack.png" alt="ship" style="display:block;border:0;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic" title="ship" width="150"></a></td> 
                         </tr> 
                         <tr style="border-collapse:collapse"> 
                          <td align="center" style="padding:0;Margin:0;padding-bottom:15px"><h2 style="Margin:0;line-height:36px;mso-line-height-rule:exactly;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;font-size:30px;font-style:normal;font-weight:bold;color:#333333">License will expire in 30 days<br></h2></td> 
                         </tr> 
                         <tr style="border-collapse:collapse"> 
                          <td class="es-m-txt-l" align="left" style="padding:0;Margin:0;padding-top:20px"><h3 style="Margin:0;line-height:22px;mso-line-height-rule:exactly;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;font-size:18px;font-style:normal;font-weight:bold;color:#333333">Dear
                              {0},</h3></td>
                         </tr> 
                         <tr style="border-collapse:collapse"> 
                          <td align="left" style="padding:0;Margin:0;padding-bottom:10px;padding-top:15px"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-size:16px;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;line-height:24px;color:#777777">Thank you for using our ETE Health Platform.</p><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-size:16px;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;line-height:24px;color:#777777">We would like to remind you that your license expires in 30 days. To continue enjoying the benefits of our services, please renew your license before the expiry date</p></td> 
                         </tr><tr>
                    <td align="left" style="padding:0;Margin:0;padding-bottom:10px;padding-top:15px"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-size:16px;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;line-height:24px;color:#777777"></p><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-size:16px;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;line-height:24px;color:#777777">Please verify with <a href="mailto:info@eyetoeyesecurity.com">info@eyetoeyesecurity.com</a> on how to renew it.</p></td> 
                    </tr> 
                       </table></td> 
                     </tr> 
                   </table></td> 
                 </tr> 
               </table></td> 
             </tr> 
           </table> 
           <table class="es-content" cellspacing="0" cellpadding="0" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;table-layout:fixed !important;width:100%"> 
             <tr style="border-collapse:collapse"> 
              <td align="center" style="padding:0;Margin:0"> 
               <table class="es-content-body" cellspacing="0" cellpadding="0" bgcolor="#ffffff" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;background-color:#FFFFFF;width:600px"> 
                 <tr style="border-collapse:collapse"> 
                  <td align="left" style="padding:0;Margin:0;padding-top:20px;padding-left:35px;padding-right:35px"> 
                   <table width="100%" cellspacing="0" cellpadding="0" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> 
                     <tr style="border-collapse:collapse"> 
                      <td valign="top" align="center" style="padding:0;Margin:0;width:530px"> 
                       <table width="100%" cellspacing="0" cellpadding="0" role="presentation" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> 
                         <tr style="border-collapse:collapse"> 
                          <td bgcolor="#eeeeee" align="left" style="Margin:0;padding-top:10px;padding-bottom:10px;padding-left:10px;padding-right:10px"> 
                           <table style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;width:500px" class="cke_show_border" cellspacing="1" cellpadding="1" border="0" align="left" role="presentation"> 
                             <tr style="border-collapse:collapse"> 
                              <td width="80%" style="padding:0;Margin:0"><h4 style="Margin:0;line-height:120%;mso-line-height-rule:exactly;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif">Information</h4></td> 
                              <td width="20%" style="padding:0;Margin:0"><h4 style="Margin:0;line-height:120%;mso-line-height-rule:exactly;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif"><br></h4></td> 
                             </tr> 
                           </table></td> 
                         </tr> 
                       </table></td> 
                     </tr> 
                   </table></td> 
                 </tr> 
                 <tr style="border-collapse:collapse"> 
                  <td align="left" style="padding:0;Margin:0;padding-left:35px;padding-right:35px"> 
                   <table width="100%" cellspacing="0" cellpadding="0" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> 
                     <tr style="border-collapse:collapse"> 
                      <td valign="top" align="center" style="padding:0;Margin:0;width:530px"> 
                       <table style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:separate;border-spacing:0px;border-color:transparent;border-style:solid;border-width:3px;border-radius:14px" width="100%" cellspacing="0" cellpadding="0" role="presentation"> 
                         <tr style="border-collapse:collapse"> 
                          <td align="center" style="Margin:0;padding-top:10px;padding-bottom:10px;padding-left:10px;padding-right:10px"> 
                           <table style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;width:500px" class="cke_show_border" cellspacing="1" cellpadding="1" border="0" align="left" role="presentation"> 
                             <tr style="border-collapse:collapse"> 
                              <td style="padding:5px 10px 5px 0;Margin:0" width="80%" align="left"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-size:15px;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;line-height:23px;color:#333333">Number of Available Licenses</p></td> 
                              <td style="padding:5px 0;Margin:0" width="20%" align="left"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-size:15px;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;line-height:23px;color:#333333"> {1}</p></td>
                       </tr><tr>
                        <td style="padding:5px 10px 5px 0;Margin:0" width="80%" align="left"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-size:15px;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;line-height:23px;color:#333333">Valid until</p></td> 
                              <td style="padding:5px 0;Margin:0" width="20%" align="left"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-size:15px;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;line-height:23px;color:#333333"> {2}</p></td>
                       </tr> 
                       <tr>
                        <td style="padding:5px 10px 5px 0;Margin:0" width="80%" align="left"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-size:15px;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;line-height:23px;color:#333333">Server ID</p></td> 
                              <td style="padding:5px 0;Margin:0" width="20%" align="left"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-size:15px;font-family:\'open sans\', \'helvetica neue\', helvetica, arial, sans-serif;line-height:23px;color:#333333"> {3}</p></td>
                       </tr> 
                           </table></td> 
                         </tr> 
                       </table></td> 
                     </tr> 
                   </table></td> 
                 </tr> 
               </table></td> 
             </tr> 
           </table> 
           <table class="es-footer" cellspacing="0" cellpadding="0" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;table-layout:fixed !important;width:100%;background-color:transparent;background-repeat:repeat;background-position:center top"> 
             <tr style="border-collapse:collapse"> 
              <td align="center" style="padding:0;Margin:0"> 
               <table class="es-footer-body" cellspacing="0" cellpadding="0" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;background-color:#FFFFFF;width:600px"> 
                 <tr style="border-collapse:collapse"> 
                  <td align="left" style="Margin:0;padding-top:35px;padding-left:35px;padding-right:35px;padding-bottom:40px"> 
                   <table width="100%" cellspacing="0" cellpadding="0" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> 
                     <tr style="border-collapse:collapse"> 
                      <td valign="top" align="center" style="padding:0;Margin:0;width:530px"> 
                       </td> 
                     </tr> 
                   </table></td> 
                 </tr> 
               </table></td> 
             </tr> 
           </table> 
           <table class="es-content" cellspacing="0" cellpadding="0" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;table-layout:fixed !important;width:100%"> 
             <tr style="border-collapse:collapse"> 
              <td align="center" style="padding:0;Margin:0"> 
               <table class="es-content-body" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;background-color:transparent;width:600px" cellspacing="0" cellpadding="0" align="center"> 
                 <tr style="border-collapse:collapse"> 
                  <td align="left" style="Margin:0;padding-left:20px;padding-right:20px;padding-top:30px;padding-bottom:30px"> 
                   <table width="100%" cellspacing="0" cellpadding="0" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> 
                     <tr style="border-collapse:collapse"> 
                      <td valign="top" align="center" style="padding:0;Margin:0;width:560px"> 
                       </td> 
                     </tr> 
                   </table></td> 
                 </tr> 
               </table></td> 
             </tr> 
           </table></td> 
         </tr> 
       </table> 
      </div>  
     </body>
    </html>

    下面的代码是替换HTML参数,在MailUtil.java中

    MessageFormat.format(buffer.toString(), array);

    注意点2(必读、重要):HTML中还有本身代码自带的“{}”,在替换的时候如果不转义,将会报错。所以从前端拿来HTML模板的时候,需要加工,将里面的{ 替换成 '{' 、将里面的} 替换成'}',如果没有替换掉,将会报以下错误

    Caused by: java.lang.NumberFormatException: For input string: "text-decoration: none;"

    其中的text-decoration: none;是我代码里的,意思就是{} 里面发现的字符串,所以转成Number的时候报错了。如下图

     

    第四步:代码准备就绪,需要去准备邮件服务器,也就是需要发邮件的参数,我这边以网易163邮箱为例

    以下就是业务代码中,发送邮件部分,你也可以根据自己需要加一层接口封装

    参数:

    mailHost:邮箱服务器地址,点此查看如何获取

    fromMail:发送邮件人

    fromMailPwd:密码,这边以163为例,点此查看如何获取163邮箱密码

    toMails:接收人地址,可以为多个,中间以“,”隔开。MailUtil中有代码可以查看

    mailTitle:邮件标题

    public static void sendMail() throws Exception {
        String mailHost = "smtp.163.com";
        String fromMail = "m18258307545@163.com";
        String fromName = "XXXX";
        String fromMailPwd = "SSTQDRCILQUPBDQB";
    
        String toMails = "m18258307545@163.com";
        String mailTitle = "m18258307545@163.com";
        String reminderDate = "30";
        HashMap<String,String> map = new HashMap<>();
        map.put("reminderDate",reminderDate);
        String mailContent = MailUtil.buildContent(map);
        MailUtil.sendMail(mailHost,fromMail,fromName,fromMailPwd,toMails,mailTitle,mailContent);
    }

    我们来看看效果吧:

    至此,发送模板邮件已完成。欢迎交流指导!

     

    展开全文
  • java发送邮件-模板

    千次阅读 2018-01-10 18:18:41
    以163网易邮箱为例,使用java发送邮件,发送以邮件时使用模板(.ftl文件转换为html)发送邮件内容,并附带上附件,可抄送给多个人。项目的结构目录如下 邮箱配置文件mail.properties参数如下#mail sender settings ...

    今天写完了一个关于使用模板发送邮件的代码,作为例子保存着,希望以后用得着,也希望能够帮助到需要帮助的人
    以163网易邮箱为例,使用java发送邮件,发送以邮件时使用模板(.ftl文件转换为html)发送邮件内容,并附带上附件,可抄送给多个人。项目的结构目录如下
    这里写图片描述

    邮箱配置文件mail.properties参数如下

    #mail sender settings
    # for example: smtp.163.com
    mail.server=smtp.163.com
    #the sender mail
    mail.sender=xxx@163.com
    #the sender nickname
    mail.nickname=
    #sender mail username
    mail.username=xxx@163.com
    #sender mail password
    mail.password=hpc2013210831xxx

    模板mail.ftl如下

    <div>
        <span>${username},你好!</span>
        <p>${content}</p>
    </div>

    邮件发送信息配置类ConfigLoader.java如下

    package com.hpc.test.mail;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    public class ConfigLoader {
        // 日志记录对象
        private static Logger log = LoggerFactory.getLogger(ConfigLoader.class);
        // 配置文件路径
        private static String mailPath = "properties/mail.properties";
        // 邮件发送SMTP主机
        private static String server;
        // 发件人邮箱地址
        private static String sender;
        // 发件人邮箱用户名
        private static String username;
        // 发件人邮箱密码
        private static String password;
        // 发件人显示昵称
        private static String nickname;
    
        static {
            // 类初始化后加载文件
            InputStream in = ConfigLoader.class.getClassLoader().getResourceAsStream(mailPath);
            Properties props = new Properties();
            try {
                props.load(in);
            } catch (IOException e) {
                log.error("load mail setting error, please check the file path:" + mailPath);
                log.error(e.toString(), e);
            }
    
            server = props.getProperty("mail.server");
            sender = props.getProperty("mail.sender");
            username = props.getProperty("mail.username");
            password = props.getProperty("mail.password");
            nickname = props.getProperty("mail.nickname");
            log.debug("load mail setting success, file path: " + mailPath);
        }
    
        public static String getServer() {
            return server;
        }
    
        public static String getSender() {
            return sender;
        }
    
        public static String getUsername() {
            return username;
        }
    
        public static String getPassword() {
            return password;
        }
    
        public static String getNickname() {
            return nickname;
        }
    
        public static void setMailPath(String mailPath) {
            ConfigLoader.mailPath = mailPath;
        }
    }
    

    邮件发送实现类MailSender.java如下

    package com.hpc.test.mail;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Properties;
    
    public class MailSender {
        // 日志记录对象
        private static Logger log = LoggerFactory.getLogger(MailSender.class);
    
        // MIME邮件对象
        private MimeMessage mimeMsg;
        // 邮件会话对象
        private Session session;
        // 系统属性
        private Properties properties;
        // Multilpart对象,邮件内容,标题,附件等内容均添加到其中后再生成
        private Multipart mp;
        // 发件人用户名
        private String username;
        // 发件人密码
        private String password;
        // 发件人昵称
        private String nickname;
    
        /**
         * 构造函数
         * @param smtp 发送主机名
         */
        public MailSender(String smtp) {
            setSmptHost(smtp);
            createMimeMessage();
        }
    
        /**
         * 设置权限坚定配置
         * @param need 是否需要权限
         * @desc
         */
        public void setNeedAuth(boolean need) {
            if (null == properties) {
                properties = System.getProperties();
            }
            if (need) {
                properties.put("mail.smtp.auth", "true");
            }
            else {
                properties.put("mail.smtp.auth", "false");
            }
            log.debug("set smtp auth success; mail.smtp.auth = " + need);
        }
    
        /**
         * 创建邮件对象
         * @description
         */
        public void createMimeMessage() {
            // 获取邮件会话对象
            session = Session.getDefaultInstance(properties, null);
            // 创建邮件MIME对象
            mimeMsg = new MimeMessage(session);
            mp = new MimeMultipart();
            log.debug("create session and mimeMessage success");
        }
    
        /**
         * 设置邮件发送的SMTP主机
         * @param smtp  发送主机名
         * @description
         */
        public void setSmptHost(String smtp) {
            if(null == properties) {
                properties = System.getProperties();
            }
            properties.put("mail.smtp.host", smtp);
            log.debug("set system properties success : mail.smtp.host = " + smtp);
        }
    
        /**
         * 设置发送邮件的主题
         * @param subject 邮件的主题
         * @throws UnsupportedEncodingException
         * @throws MessagingException
         * @desc
         */
        public void setSubject(String subject) throws UnsupportedEncodingException, MessagingException {
            mimeMsg.setSubject(MimeUtility.encodeText(subject, "utf-8", "B"));
            log.debug("set mail subject success, subject = " +subject);
        }
    
        public void setBody(String mailBody) throws MessagingException {
            BodyPart bp = new MimeBodyPart();
            bp.setContent("" + mailBody, "text/html;charset=utf-8");
            mp.addBodyPart(bp);
            log.debug("set mail body content success, mailBody = " + mailBody);
        }
    
        /**
         * 添加邮件附件,附件可为多个
         * @param fileMap 文件绝对路径map集合
         * @throws MessagingException
         */
        public void setFileAffix(Map<String, String> fileMap) throws MessagingException, UnsupportedEncodingException {
            // 获取附件
            for (String file: fileMap.keySet()) {
                // 创建一个存放附件的BodyPart对象
                BodyPart bp = new MimeBodyPart();
                // 获取文件路径
                String filePath = fileMap.get(file);
                String[] fileNames = filePath.split("/");
                // 获取文件名
                String fileName = fileNames[fileNames.length-1];
                // 设置附件名称,附件名称为中文时先用utf-8编码
                bp.setFileName(MimeUtility.encodeWord(fileName, "utf-8", null));
                FileDataSource fields = new FileDataSource(filePath);
                bp.setDataHandler(new DataHandler(fields));
                // multipart中添加bodypart
                mp.addBodyPart(bp);
                log.debug("mail add file success, filepath = " + filePath);
            }
            log.debug("setFileAffix end with success");
        }
    
        /**
         * 设置发件人邮箱地址
         * @param sender 发件人邮箱地址
         * @throws UnsupportedEncodingException
         * @throws MessagingException
         * @desc
         */
        public void setSender(String sender) throws UnsupportedEncodingException, MessagingException {
            nickname = MimeUtility.encodeText(nickname, "utf-8", "B");
            mimeMsg.setFrom(new InternetAddress(nickname + "<" + sender + ">"));
            log.debug("set mail sender and nickname success, sender = " + sender);
        }
    
        /**
         * 设置收件人邮箱地址 可以设置多个收件人
         * @param receivers 收件人邮箱地址List集合
         * @throws MessagingException
         * @desc
         */
        public void setReceiver(String[] receivers) throws MessagingException {
            // 将收件人数组设置为InternetAddress数组类型
            List<InternetAddress> receiverList = new ArrayList<InternetAddress>();
            for (String receiver : receivers) {
                receiverList.add(new InternetAddress(receiver));
            }
            InternetAddress[] addresses = receiverList.toArray(new InternetAddress[receivers.length]);
            mimeMsg.setRecipients(Message.RecipientType.TO, addresses);
            log.debug("set mail receiver success, the number of receivers is = " + addresses.length);
        }
    
        /**
         * 设置抄送人邮箱地址
         * @param copyTos 抄送人邮箱地址
         * @throws MessagingException
         * @desc
         */
        public void setCopyTo(String[] copyTos) throws MessagingException {
            // 将抄送人数组设置为InternetAddress数组类型
            List<InternetAddress> copyToList = new ArrayList<InternetAddress>();
            for (String copyto : copyTos) {
                copyToList.add(new InternetAddress(copyto));
            }
            InternetAddress[] addresses = copyToList.toArray(new InternetAddress[copyTos.length]);
            mimeMsg.setRecipients(Message.RecipientType.CC, addresses);
            log.debug("set mail copyto receiver success, the number of copyTos is  " + copyTos.length);
        }
    
        /**
         * 设置发件人用户名密码进行发送邮件操作
         * @throws MessagingException
         * @desc
         */
        public void sendout() throws MessagingException {
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            Session mailSession = Session.getDefaultInstance(properties, null);
            Transport transport = mailSession.getTransport("smtp");
            transport.connect((String) properties.get("mail.smtp.host"), username, password);
            transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
            transport.close();
            log.debug("send mail success");
        }
    
        /**
         * 设置发件人用户名、密码、昵称
         * @param username 发件人用户名
         * @param password 发件人密码
         * @param nickname 发件人昵称
         * @desc
         */
        public void setNamePass(String username, String password, String nickname) {
            this.username = username;
            this.password = password;
            this.nickname = nickname;
        }
    }

    邮件发送工具类MailUtil.java

    package com.hpc.test.mail;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import javax.mail.MessagingException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    public class MailUtil {
        private static Logger log = LoggerFactory.getLogger(MailUtil.class);
    
        /**
         * 根据模版名称查找模版,加载目标内容后发送邮件,抄送给copyTos
         * @param receivers 收件人邮箱地址数组
         * @param copyTos 抄送人邮箱地址数组
         * @param subject 邮件主题
         * @param fileMap 附件路径map集合
         * @param map 邮件内容与模板内容转换对象
         * @param templateName 模板文件名称
         * @throws UnsupportedEncodingException
         * @throws MessagingException
         *
         */
        public static void sendMailFileByTemplateWithCopyto(String[] receivers, String[] copyTos, String subject, Map<String, String> fileMap, Map<String, String> map, String templateName) throws UnsupportedEncodingException, MessagingException {
            String mailBody = "";
            String server = ConfigLoader.getServer();
            String sender = ConfigLoader.getSender();
            String username = ConfigLoader.getUsername();
            String password = ConfigLoader.getPassword();
            String nickname = ConfigLoader.getNickname();
            MailSender mail = new MailSender(server);
            mail.setNeedAuth(true);
            mail.setNamePass(username, password, nickname);
            mailBody = TemplateFactory.genrateHtmlFromFtl(templateName, map);
            mail.setSubject(subject);
            mail.setFileAffix(fileMap);
            mail.setBody(mailBody);
            mail.setReceiver(receivers);
            mail.setSender(sender);
            mail.sendout();
        }
    }
    展开全文
  • 在项目需要发送邮件,普通内容的邮件觉得太单调、太丑,没逼格,所以说直接把用到的邮件内容做成一个html模板,发送之前将对应参数替换掉,发送html内容的高逼格邮件。  首先需要引用jar包,这就不多说了,直接贴...
  • 项目中经常会遇到发送邮件的问题,有时还需要发送html格式的邮件,如果直接在java文件硬编码写html,那么维护起来将会非常麻烦,利用Velocity模板引擎可以解决这个问题,使得业务处理和视图渲染相分离,方便维护。...
  • Java Mail+Thymeleaf模板引擎实现发送HTML格式邮件 基于Spring boot 1.5,Spring boot 2.x请使用Spring boot mail 1.依赖坐标 // buildscript 代码块中脚本优先执行 buildscript { //springBootVersion = '1.5.2....
  •  RFC882文档规定了如何编写一封简单的邮件(纯文本邮件),一封简单的邮件包含邮件头和邮件体两个部分,邮件头和邮件体之间使用空行分隔。  邮件头包含的内容有: from字段 --用于指明发件人 to字段 --用于...
  • java发送email邮件.

    2017-02-20 18:15:46
    demo介绍:http://blog.csdn.net/love_xiolan/article/details/56016576 java发送email邮件 1.发送普通email邮件 2.发送带附件的email邮件 3.邮件抄送和密送 4.发送html邮件 5.发送模板文件
  • 首先介绍了发送一般邮件,然后介绍了发送富文本(html邮件及以velocity为模板发送邮件。   邮件发送分为为三步:创建邮件发送器、编写邮件发送邮件。   spring的JavaMailSenderImpl提供了强大的...
  • java 利用spring JavaMailSenderImpl发送邮件,支持普通文本、附件、html、velocity模板 博客分类: Java Spring 本文主要介绍利用JavaMailSenderImpl发送邮件。首先介绍了发送一般邮件,然后介绍了...
  • 邮件发送内容模板,负责到word里面,变量命名如下,如果有集合,在下文会讲到: 把word转html,使用筛选方式: 生产的html默认编码格式为gb2312,调整html编码格式,并存为ftl文件格式: 最后清除掉ftl文档...

空空如也

空空如也

1 2 3 4 5 ... 9
收藏数 174
精华内容 69
关键字:

java发送html模板邮件

java 订阅