zoukankan      html  css  js  c++  java
  • java调用html模板发送html内容的邮件

      在项目需要发送邮件,普通内容的邮件觉得太单调、太丑,没逼格,所以说直接把用到的邮件内容做成一个html模板,发送之前将对应参数替换掉,发送html内容的高逼格邮件。

      首先需要引用jar包,这就不多说了,直接贴代码:

    1.发送邮件处理

     1            String host = "";
     2            String mailFrom = "";
     3            String mailPass = "";
     4            Properties props=new Properties();
     5            props.put("mail.smtp.host",host);
     6            props.put("mail.smtp.auth", "true"); 
     7            Session s=Session.getInstance(props);
     8            MimeMessage message=new MimeMessage(s);
     9     
    10            //  给消息对象设置发件人/收件人/主题/发信时间
    11           try{
    12               InternetAddress from=new InternetAddress(mailFrom);
    13               message.setFrom(from);
    14               InternetAddress to=new InternetAddress(mailto);
    15               message.setRecipient(Message.RecipientType.TO,to);
    16               message.setSubject(title);
    17               message.setSentDate(new Date());
    18         
    19               //给消息对象设置内容
    20               BodyPart mdp=new MimeBodyPart();//新建一个存放信件内容的BodyPart对象
    21               mdp.setContent(htmlContent,"text/html;charset=UTF-8");//给BodyPart对象设置内容和格式/编码方式
    22               Multipart mm=new MimeMultipart();//新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)
    23               mm.addBodyPart(mdp);//将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
    24               message.setContent(mm);//把mm作为消息对象的内容
    25               message.saveChanges();
    26               Transport transport=s.getTransport("smtp");
    27               transport.connect(host,mailFrom,mailPass);
    28               transport.sendMessage(message,message.getAllRecipients());
    29               transport.close();
    30               return true;
    31           }
    32           catch (Exception e) {
    33               e.printStackTrace();
    34                  return false;
    35           }        

      调用的时候传三个参数,邮件接收人 mailto ,邮件主题 title,邮件的html内容 htmlContent

    2.获取html模板文件路径

    3.读取html模板文件的内容

    4.对模板中的参数进行替换

  • 相关阅读:
    团队作业
    第四次作业
    第三次作业
    从电梯问题,看c和c++之间的区别(有点懂了)错觉错觉
    团队作业2
    游戏方案
    电梯调度程序4
    电梯调度程序3
    电梯调度程序2
    电梯调度程序1
  • 原文地址:https://www.cnblogs.com/weihanli/p/sendHtmlMail.html
Copyright © 2011-2022 走看看