关于这个工具的创作:相信大家都有找工作的经历,在简历投递的时候是否有这样的烦恼?点对点的发送邮件时,不停的复制粘贴自己的简历发送,在这一期间不仅浪费了大家相当多的一部分时间,而且发送简历的效率也不是很高。于是自己便做了一个这样的小工具,能够进行批量、群发邮件的功能。

      一、开发前准备:

      必要的jar包:mail.jar、commons-email-1.1.jar、activation.jar

     

     二、代码编写:

     MailSenderInfo.java  封装Mail普通dojo类

   

package cn.com.mes.mail;

import java.util.Date;
/**
 * 封装邮件发送对象类
 * @author HuangXiaoyong
 */
public class MailSenderInfo {
        //邮件登录账号
	private String username = "";
        //邮件登录密码
	private String password = "";
        //邮件服务器地址
	private String hostName = "";
        //发件人邮箱地址
	private String from = "";
        //邮件标题
	private String title = "";
        //要发送Html文本路径
	private String htmlPath = "";
        //发送时间
	private Date sendDate = null;
	
	public MailSenderInfo (){
		
	}
	

	public MailSenderInfo(String username, String password, String hostName,
			String from, String title) {
		super();
		this.username = username;
		this.password = password;
		this.hostName = hostName;
		this.from = from;
		this.title = title;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getHostName() {
		return hostName;
	}

	public void setHostName(String hostName) {
		this.hostName = hostName;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getHtmlPath() {
		return htmlPath;
	}


	public void setHtmlPath(String htmlPath) {
		this.htmlPath = htmlPath;
	}


	public Date getSendDate() {
		return sendDate;
	}


	public void setSendDate(Date sendDate) {
		this.sendDate = sendDate;
	}
}

 

   2.MailUtils邮件发送工具类

package cn.com.mes.mail;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 邮件发送工具类
 * @author HuangXiaoyong
 */
public class MailUtils {
	//邮件服务器地址
	public static final String EMAIL_HOST = "email.host";
	//邮箱登录账号
	public static final String EMAIL_USERNAME ="email.username";
	//邮箱登录密码
	public static final String EMAIL_PASSWORD ="email.password";
	//发送邮件标题
	public static final String EMAIL_TITLE ="email.title";
	//发件人邮箱地址
	public static final String EMAIL_FROM = "email.from";
	//发送Html简历路径
	public static final String EMAIL_HTML_PATH = "email.html.path";
	//发送简历时间
	public static final String EMAIL_SEND_DATE = "email.senddate";
	//收件人邮箱地址
	public static final String EMAIL_TO = "email.to";
	
	public static void main(String[] args) throws Exception{
		 
	}
	
	private static List<String> mailAddList = new ArrayList<String>(); 
	
	/** 
	 * 将某个日期以yyyy-MM-dd HH:mm:ss格式转化成字符串 
	 * @param date 
	 * @return str 
	 */ 
	public static String formatDateToString(Date date)
	{ 
	  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
	  String str = sdf.format(date); 
	  return str; 
	} 
	
	/**
	 * 将日期字符串转化成Date对象
	 * @param strDate
	 * @return
	 */
	public static Date formatStringToDate(String strDate){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;  
		try{
			date = sdf.parse(strDate);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		 
		  return date; 
	}
	
	
	/**
	 * 设置邮件属性
	 * @param mailInfo
	 * @return
	 */
	public static boolean setEMailProperties(MailSenderInfo mailInfo){
		boolean flag = false;
		Properties props = new Properties();
		try{
			props.load(new FileInputStream(System.getProperty("user.dir")+"\\mail.properties"));
			props.setProperty(EMAIL_HOST, mailInfo.getHostName());
			props.setProperty(EMAIL_USERNAME, mailInfo.getUsername());
			props.setProperty(EMAIL_PASSWORD, mailInfo.getPassword());
			props.setProperty(EMAIL_TITLE, mailInfo.getTitle());
			props.setProperty(EMAIL_FROM, mailInfo.getFrom());
			props.setProperty(EMAIL_HTML_PATH, mailInfo.getHtmlPath());
			props.setProperty(EMAIL_SEND_DATE, formatDateToString(mailInfo.getSendDate()));
			FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir")+"\\mail.properties");
			props.store(fos, "");
			fos.close();
			
			flag = true;
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
		return flag;
	}
	
	
	/**
         *  获取邮件属性
         * @return
         */
	public static MailSenderInfo getMailSenderInfo(){
		
		MailSenderInfo mailInfo = new MailSenderInfo();
		Properties props = new Properties();  
		try{
			props.load(new FileInputStream(System.getProperty("user.dir")+"\\mail.properties"));
		}catch(Exception ex){
			ex.printStackTrace();
		}
		mailInfo.setHostName(props.getProperty(EMAIL_HOST));
		mailInfo.setUsername(props.getProperty(EMAIL_USERNAME));
		mailInfo.setPassword(props.getProperty(EMAIL_PASSWORD));
		mailInfo.setFrom(props.getProperty(EMAIL_FROM));;
		mailInfo.setSendDate(formatStringToDate(props.getProperty(EMAIL_SEND_DATE)));
		mailInfo.setTitle(props.getProperty(EMAIL_TITLE));
		mailInfo.setHtmlPath(props.getProperty(EMAIL_HTML_PATH));
		return mailInfo;
		
	}

        /**
         * 收件人的数目
         * @return
         */
	public static int getToCounts(){
		return mailAddList.size();
	}

        
	
	/**
	 * 获取发送邮件列表从指定的文件中
	 * @param path
	 * @return
	 */
	public static List<String> getToList(String path){
		String strEMailAdd = "";
		try{
			//从文件中读取抓取的电子邮件
			strEMailAdd = getStringBufferText(path);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		//将读取的邮件地址字符串分割,添加到List集合中
		String[] strLists = strEMailAdd.split(",");
		for(String list : strLists){
			mailAddList.add(list);
		}
		return mailAddList;
	}
	
	/**
	 *  获取指定文件的内容
	 * 
	 * @param path  要读取文件的路径
	 * @return
	 * @throws Exception
	 */
	public static String  getStringBufferText(String path){
		StringBuffer sbf = new StringBuffer();
		FileReader  read = null;
		BufferedReader br = null;
		try{
			read = new FileReader (path);
			br = new BufferedReader(read);
				
			String info = null;
			while((info = br.readLine())!=null) {
				sbf.append(info);
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			try{
				br.close();
				read.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
		return sbf.toString();
		
	}
	
}

 

 

  3.MailSender类:发送邮件封装类

package cn.com.mes.mail;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

/**
 * 发送邮件封装类
 * @author HuangXiaoyong
 */
public class MailSender implements Runnable {
	
	protected Logger logger =  Logger.getLogger(MailSender.class);
	
	private MailSenderInfo mailInfo =null;
	
	private final String tipInfoFormat = "一共需要发送{0}封邮件,成功发送{1}封,失败发送{2}封。\n\r失败邮件列表地址:{3}"; 
	 
	 
	 

	
	public MailSender(){
		mailInfo = MailUtils.getMailSenderInfo();
	}
	
	public static void main(String[] args){
		Runnable run = new  MailSender();
		run.run();
	}
	
	@Override
	public void run() {
                String addressPath ="D:\\test\\09-09-09.txt";
                List<String> list =MailUtils.getToList(addressPath);
		this.sendHtmlEmail(mailInfo,list);
	}
	
	
	 public String getResultInfo(int sum ,int success,int fail,List<String> failList ) {     
	        return MessageFormat.format(this.tipInfoFormat, sum,success,    
	        		fail, failList.toString());    
	 }   

	public void sendHtmlEmail(MailSenderInfo info,
                List<String> emailAddresslist,
                javax.swing.JProgressBar bar){
            List<String> fialAddressList = new ArrayList<String>();
            bar.setMinimum(0);
            bar.setMaximum(emailAddresslist.size()-1);
            //收件人邮件地址list集合
            int failCount = 0;
            int successCount = 0;
            try{
                    for(int i=0;i<emailAddresslist.size();i++){
                          bar.setValue(i);
                          String contentText = MailUtils.getStringBufferText(info.getHtmlPath());
                            boolean flag = sendSingleHtmlEmail(info.getUsername(),
                                            info.getPassword(),
                                            info.getHostName(),
                                            info.getFrom(),
                                            emailAddresslist.get(i),
                                            info.getTitle(),
                                            contentText,
                                            info.getSendDate());
                            if(flag){
                                    successCount++;
                            }else{
                                    fialAddressList.add(emailAddresslist.get(i));
                                    failCount++;
                            }
                            //发送10封邮件,当前线程休眠2秒
                             if(i%10 == 0){	
                                     Thread.currentThread().sleep(1000*2);
                             }
                            
                    }
            }catch(Exception ex){
                    ex.printStackTrace();	
            }
            logger.info(getResultInfo(emailAddresslist.size(),successCount,failCount,fialAddressList));
            
        }

	public void sendHtmlEmail(MailSenderInfo info,List<String> emailAddresslist) {
		List<String> fialAddressList = new ArrayList<String>();
		//收件人邮件地址list集合
		int failCount = 0;
		int successCount = 0;
		try{
			for(int i=0;i<emailAddresslist.size();i++){
                              String contentText = MailUtils.getStringBufferText(info.getHtmlPath());
				boolean flag = sendSingleHtmlEmail(info.getUsername(),
						info.getPassword(),
						info.getHostName(),
						info.getFrom(),
						emailAddresslist.get(i),
						info.getTitle(),
						contentText,
						info.getSendDate());
				if(flag){
					successCount++;
				}else{
					fialAddressList.add(emailAddresslist.get(i));
					failCount++;
				}
				//发送10封邮件,当前线程休眠2秒
				 if(i%10 == 0){	
					 Thread.currentThread().sleep(1000*2);
				 }
			}
		}catch(Exception ex){
			ex.printStackTrace();	
		}
		logger.info(getResultInfo(emailAddresslist.size(),successCount,failCount,fialAddressList));
		
	}
	
	/**
	 * 
	 * 发送单个Html文本邮件
	 * @param username
	 * @param password
	 * @param host
	 * @param from
	 * @param to
	 * @param title
	 * @param context
	 * @return
	 */
	public boolean sendSingleHtmlEmail(String username,
				    String password,String host,
				    String from, String to,
				    String title, String context,Date sendDate ) throws Exception{
		logger.info(new Date().toString()+": 开始向"+to+"邮箱发送邮件....");

		boolean flag = false;
		HtmlEmail  email =new HtmlEmail();
		email.setAuthentication(username,password);
		email.setHostName(host); 
		email.setCharset("GB2312"); 
		//设置邮件标题
        email.setSubject(title); 
        
        try{
        	//设置发件人
	        email.setFrom(from);
	        //设置收件人
	        email.addTo(to); 
	        //Html邮件上下文,邮件内容
	        email.setHtmlMsg(context);
	        //设置邮件发送时间
	        email.setSentDate(sendDate);
	        email.send();
	        flag = true;
	        logger.info(new Date().toString()+":成功发送邮件");
        }catch(Exception ex){
        	logger.error("发送邮件出现异常!");
        	throw ex;
        }
		return flag;
	}

	
	
}

 

 

这些是主要后台编写的类,运行效果如下:

首先设置好邮件属性

 

在添加发送人的邮件列表(.txt)文件,每个邮件地址用逗号(",")分隔开

 


 

swing前台代码就不在这里罗列了

 

不足的地方:前台属性设置的时候没有做校验判断。

 

遇到的问题有:发送邮件群发到一定的数量的时候,发送邮件失败。虽然我这里采用了多线程,问题依旧存在。