javaMail发送邮件实例

背景:最近项目里有个实时发送邮件的功能,今天闲下来整理 一下,记录下来方便以后直接使用。

代码:

  1 package com.dzf.utils;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.text.SimpleDateFormat;
  7 import java.util.ArrayList;
  8 import java.util.Date;
  9 import java.util.List;
 10 import java.util.Properties;
 11 
 12 import javax.activation.DataHandler;
 13 import javax.activation.FileDataSource;
 14 import javax.mail.Message;
 15 import javax.mail.Session;
 16 import javax.mail.Transport;
 17 import javax.mail.internet.InternetAddress;
 18 import javax.mail.internet.MimeBodyPart;
 19 import javax.mail.internet.MimeMessage;
 20 import javax.mail.internet.MimeMultipart;
 21 
 22 import org.slf4j.Logger;
 23 import org.slf4j.LoggerFactory;
 24 
 25 /**
 26  *    邮件发送工具类 
 27  * @author xxx
 28  * @date 2018年1月22日
 29  * @time 22:43:40
 30  */
 31 public class SendEmailUtil implements Runnable {
 32     private static Logger log =  LoggerFactory.getLogger(SendEmailUtil.class);
 33     private static Properties prop = new Properties();
 34     private List<String> toEmilList = new ArrayList<String>();//用于指定收件人的邮箱
 35     private List<String> ccEmilList = new ArrayList<String>();//用于抄送的收件人的邮箱
 36     public List<String> getCcEmilList() {
 37         return ccEmilList;
 38     }
 39     public void setCcEmilList(List<String> ccEmilList) {
 40         this.ccEmilList = ccEmilList;
 41     }
 42     public SendEmailUtil(List<String> toEmilList, List<String> ccEmilList) {
 43         super();
 44         this.toEmilList = toEmilList;
 45         this.ccEmilList = ccEmilList;
 46     }
 47     public List<String> getToEmilList() {
 48         return toEmilList;
 49     }
 50     public void setToEmilList(List<String> emilList) {
 51         this.toEmilList = emilList;
 52     }
 53     public SendEmailUtil(List<String> emilList) {
 54         super();
 55         this.toEmilList = emilList;
 56     }
 57     
 58     public SendEmailUtil() {
 59         super();
 60     }
 61     static{
 62         InputStream in = SendEmailUtil.class.getClassLoader().getResourceAsStream("emil_config.properties");
 63         try {
 64             prop.load(in);
 65         } catch (IOException e) {
 66             e.printStackTrace();
 67             log.error("读取配置失败,异常信息{}",e.toString());
 68             throw new RuntimeException("读取邮件配置文件失败");
 69         }
 70     }
 71     @Override
 72     public void run() {
 73         try {
 74             log.info("邮件创建开始了。。。。");
 75             //1.创建session
 76             Session session = Session.getInstance(prop);
 77             //2.开启session的debug模式,可以查看出email发送的情况
 78             session.setDebug(true);
 79             //3.连接发件服务器
 80             Transport trans = session.getTransport();
 81             trans.connect(prop.getProperty("mail.host"),prop.getProperty("mail.name"), prop.getProperty("mail.password"));
 82             //4.创建邮件
 83             Message message = createMessageMail(session);
 84             //发送邮件
 85             trans.sendMessage(message, message.getAllRecipients());
 86             trans.close();
 87         } catch (Exception e) {
 88             log.error("创建邮件发生异常:异常为{}",e.toString());
 89             e.printStackTrace();
 90         }
 91     }
 92     /**
 93      * 组装邮件
 94      * @param session
 95      */
 96     private Message createMessageMail(Session session)throws Exception {
 97         //创建邮件对象
 98         MimeMessage mimeMessage = new MimeMessage(session);
 99         //设置邮件的基本信息
100         //发件人
101         mimeMessage.setFrom(new InternetAddress(prop.getProperty("mail.from")));
102         //收件人
103         InternetAddress[] addressTo = new InternetAddress[toEmilList.size()];
104         for(int i =0 ;i<toEmilList.size();i++){
105             addressTo[i]=new InternetAddress(toEmilList.get(i));
106         }
107         //抄送人
108         InternetAddress[] addressCc = new InternetAddress[ccEmilList.size()];
109         for(int i =0 ;i<ccEmilList.size();i++){
110             addressCc[i]=new InternetAddress(ccEmilList.get(i));
111         }
112         mimeMessage.setRecipients(Message.RecipientType.TO, addressTo);
113         if(ccEmilList.size()>0){
114             mimeMessage.setRecipients(Message.RecipientType.CC, addressCc);
115         }
116         //邮件标题
117         mimeMessage.setSubject("私人定制-系统通知");
118         
119         //邮件正文
120         MimeBodyPart bodyPart = new MimeBodyPart();
121         SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
122         Date date = new Date();
123         String str = simple.format(date);
124         bodyPart.setContent("亲爱得用户:<br/>&nbsp;&nbsp;&nbsp;&nbsp;<p>你好,你与"+str+"登录私人定制,如果不是本人登录,你的密码可能已经泄露!请立即前往官网修改密码。如果是你非别人登录,请你忽略此消息!谢谢!</p>","text/html;charset=utf-8");
125         //TODO添加附件,图片之类
126         MimeBodyPart attach = new MimeBodyPart();
127         File file = new File("e:/generatorConfig.xml");
128         DataHandler dh= new DataHandler(new FileDataSource(file));
129         attach.setDataHandler(dh);
130         
131         //描述数据关系
132         MimeMultipart multipart = new MimeMultipart();
133         multipart.addBodyPart(bodyPart);
134         multipart.addBodyPart(attach);
135         mimeMessage.setContent(multipart);
136         mimeMessage.saveChanges();
137         return mimeMessage;
138     }
139     public static void main(String[] args) {
140         List<String> toEmilList = new ArrayList<String>();
141         toEmilList.add("xxxx23319@qq.com");
142         toEmilList.add("xxxx39686@qq.com");
143         List<String> ccEmilList = new ArrayList<String>();
144         ccEmilList.add("xxxx79285@qq.com");
145         SendEmailUtil email = new SendEmailUtil(toEmilList, ccEmilList);
146         new Thread(email).start();//启动一个线程
147     }
148 }

配置文件 emil_config.properties

1 mail.host=smtp.163.com
2 mail.transport.protocol=smtp
3 mail.smtp.auth=true
4 mail.name=xxxxxx@163.com
5 #shouquanma
6 mail.password=xxxxxxx
7 mail.from=xxxxxx@163.com

有关邮件发送遇到的问题我的另一篇随笔里有写  传送门:http://www.cnblogs.com/zfding/p/8324784.html

原文地址:https://www.cnblogs.com/zfding/p/8324978.html