1. 程式人生 > >javaMail郵件傳送

javaMail郵件傳送

MailAuthenticator.java

package com.sunrise.jop.common.mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**  
 * 伺服器郵箱登入驗證  
 * */  
public class MailAuthenticator extends Authenticator{  
    private String userName = null;//用於傳送郵件的郵箱  
  
    private String password = null;//郵箱密碼  
  
    public MailAuthenticator() {  
    }  
  
    public MailAuthenticator(String username, String password) {  
        this.userName = username;  
        this.password = password;   
    }  
  
    protected PasswordAuthentication getPasswordAuthentication() {  
        return new PasswordAuthentication(userName, password);  
    }  
      
    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;  
    }  
}  

MailSendeBean.java
package com.sunrise.jop.common.mail;

import java.io.File;
import java.util.List;
import java.util.Properties;

/**
 * 郵件資訊bean
 * */
public class MailSendeBean {

	// 郵箱地址
	private String emailAddress;

	// 主題
	private String subject;

	// 內容
	private String content;

	// 附件
	private List<File> attachFiles;
	
	
	public MailSendeBean() {
	
	}

	public MailSendeBean(String emailAddress, String subject, String content) {
		this.emailAddress = emailAddress;
		this.subject = subject;
		this.content = content;
	}
	
	/**
	 * emailAddress 郵箱地址
	 * subject 主題
	 * content 內容
	 * attachFiles 附件
	 * */
	public MailSendeBean(String emailAddress, String subject, String content,
			List<File> attachFiles) {
		this.emailAddress = emailAddress;
		this.subject = subject;
		this.content = content;
		this.attachFiles = attachFiles;
	}

	public String getEmailAddress() {
		return emailAddress;
	}

	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public List<File> getAttachFiles() {
		return attachFiles;
	}

	public void setAttachFiles(List<File> attachFiles) {
		this.attachFiles = attachFiles;
	}

    

}
MailSender.java
package com.sunrise.jop.common.mail;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;  
import java.util.List;  
import java.util.Properties;  
  











import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;  
import javax.mail.Multipart;
import javax.mail.Session;  
import javax.mail.Transport;  
import javax.mail.internet.AddressException;  
import javax.mail.internet.InternetAddress;  
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;  
import javax.mail.internet.MimeMessage.RecipientType;  
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
  
/**  
 * 郵件傳送器
 * */  
public class MailSender {  
  
    //傳送郵件的props檔案  
    private final transient Properties props = System.getProperties();  
  
    private transient MailAuthenticator authenticator;//郵件伺服器登入驗證    
  
    private  transient Session session;//郵箱session  
    
    private final int MAX_SEND_NUMBER = 100;//每次最大發送多少封郵件 
    
    private final long SLEEP_TIME  = 1000 * 60 * 2; //休息時間
    
    private final int REPEAT_TIME = 3 ;// 郵件重發次數
    
    /**    
     * 初始化郵件傳送器    
     *    
     * @param smtpHostName    
     * SMTP郵件伺服器地址    
     * @param username    
     * 傳送郵件的使用者名稱(地址)    
     * @param password    
     * 傳送郵件的密碼    
     */   
    public MailSender(final String smtpHostName, final String username,    
            final String password) {    
        init(username, password, smtpHostName);    
    }   
  
    /**    
     * 初始化郵件傳送器    
     *    
     * @param username    
     * 傳送郵件的使用者名稱(地址),並以此解析SMTP伺服器地址    
     * @param password    
     * 傳送郵件的密碼    
     */   
    public MailSender(final String username, final String password) {    
        //通過郵箱地址解析出smtp伺服器,適合大多數郵箱   
        final String smtpHostName = "smtp." + username.split("@")[1];    
        init(username, password, smtpHostName);    
    }    
    /**    
     * 初始化    
     *    
     * @param username    
     * 傳送郵件的使用者名稱(地址)    
     * @param password    
     * 密碼    
     * @param smtpHostName    
     * SMTP主機地址    
     */   
    private void init(String username, String password, String smtpHostName) {    
        // 初始化props    
        props.put("mail.smtp.auth", "true");    
        props.put("mail.smtp.host", smtpHostName);    
        // 驗證    
        authenticator = new MailAuthenticator(username, password);    
        // 建立session    
        session = Session.getInstance(props, authenticator);    
    } 
    
    /**
     * 群發郵件
     * @throws Exception 
     * */
    public String sendToManyUser( List<MailSendeBean> mailBeanList ) throws Exception{
    	if(mailBeanList==null||mailBeanList.size()==0)
    	{
    		return "請設定郵件相關引數\n	";
    	}
    	StringBuffer stringBuffer = new StringBuffer();
    	int count = 0 ;
    	for( int i = 0 ; i < mailBeanList.size() ; i++ ){
    		count ++;
    		MailSendeBean mailBean = mailBeanList.get(i);
    		stringBuffer.append(this.sendToOneUser(mailBean));  
    		if(this.MAX_SEND_NUMBER==count){
    			count = 0 ;
    			Thread.sleep(SLEEP_TIME );
    		}
    	}
    	return stringBuffer.toString();
    	
    }
    
    
    /**
     * 單個郵件傳送
     * @throws Exception 
     * */
   public String sendToOneUser(MailSendeBean mailSendeBean) throws Exception{
    	
    	if(mailSendeBean==null) return "請設定郵件相關引數\n	";
    	
    	//返回提示資訊
    	String result = "["+mailSendeBean.getEmailAddress() +"]傳送郵件成功\n	" ;
    	
    	 // 建立mime型別郵件    
        final MimeMessage message = new MimeMessage(session);    
        // 設定發信人    
        message.setFrom(new InternetAddress(authenticator.getUserName()));    
        // 設定收件人    
        message.setRecipient(RecipientType.TO, new InternetAddress(mailSendeBean.getEmailAddress()));    
        // 設定主題    
        message.setSubject(mailSendeBean.getSubject());  
        // 設定傳送時間  
        message.setSentDate(new Date());  
          
        // 向multipart物件中新增郵件的各個部分內容,包括文字內容和附件
        Multipart multipart = new MimeMultipart();
        
        // 新增郵件正文
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(mailSendeBean.getContent().toString(), "text/html;charset=UTF-8");
        multipart.addBodyPart(contentPart);
        List<File> attachFiles =   mailSendeBean.getAttachFiles();
        if(attachFiles!=null&&attachFiles.size() >0 ){
        	for( int i = 0 ; i <  attachFiles.size() ; i++){
        		File attchFile =  attachFiles.get(i);
        		if(attchFile != null){
        			 BodyPart attachmentBodyPart = new MimeBodyPart();
        	            DataSource source = new FileDataSource(attchFile);
        	            attachmentBodyPart.setDataHandler(new DataHandler(source));
        	             //MimeUtility.encodeWord可以避免檔名亂碼
        	            attachmentBodyPart.setFileName(MimeUtility.encodeWord(attchFile.getName()));
        	            multipart.addBodyPart(attachmentBodyPart);
        		}
        	}
        }
        
      // 將multipart物件放到message中
        message.setContent(multipart);
        try{
        	  Transport.send(message); 
    	}catch(Exception e){
    		e.printStackTrace();
    		this.repeatSend(message); //重發
    	}
  	
		return result;
    	
    }
    
   /**
    * 郵件傳送失敗後,可以重發3次的處理
    * */
   private void repeatSend(MimeMessage message){
	   if(message!=null){
		   for( int i = 0 ;  i < this.REPEAT_TIME ; i++){
			   try{
		        	 Transport.send(message);
		        	  break;
		    	  }catch(Exception e){
		    		e.printStackTrace();
		    	}
		   }
	   }
   }

}  


MailSenderDemo.java
package com.sunrise.jop.common.mail;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 郵件傳送demo
 * */
public class MailSenderDemo {

	//建立郵件伺服器
	private MailSender createMailSender(){
		String smtpHostName = "imap.exmail.qq.com";   //郵件伺服器
        String username = "[email protected]"; 
        String password = "JiangPeng341341";  
        MailSender mailSender = new MailSender(smtpHostName,username,password);
        return mailSender;
        
	}
	
	//多個使用者郵件傳送
	private void sendToManyUser() throws Exception{
		//初始化郵件伺服器
		MailSender mailSender = this.createMailSender();
		
		//第一個使用者
		
		//建立郵件bean
		String emailAddress1 = "[email protected]";  
        String subject1 = "郵件主題測試1";  
        String content1 = "郵件內容測試1"; 
        //附件
        File txtFile1 = new File("D:"+File.separator+ "emailTest" + File.separator + "testText.txt");
        File docFile1 = new File("D:"+File.separator+ "emailTest" + File.separator + "testDoc.doc");
        File excelFile1 = new File("D:"+File.separator+ "emailTest" + File.separator + "testExcel.xls");
        File photoFile1 = new File("D:"+File.separator+ "emailTest" + File.separator + "testPhoto.jpg");
        
        List<File> attchFiles1 = new ArrayList<File>();
        attchFiles1.add(txtFile1);   attchFiles1.add(docFile1);
        attchFiles1.add(excelFile1);   attchFiles1.add(photoFile1);
        
        //封裝單個郵件bean
        MailSendeBean mailSendeBean1 = new MailSendeBean( emailAddress1, subject1,  content1,attchFiles1);
        
        
        //第二個使用者
        String emailAddress2 = "[email protected]";  
        String subject2 = "郵件主題測試2";  
        String content2 = "郵件內容測試2"; 
        //附件
        File txtFile2 = new File("D:"+File.separator+ "emailTest" + File.separator + "testText.txt");
        File docFile2 = new File("D:"+File.separator+ "emailTest" + File.separator + "testDoc.doc");
        
        
        List<File> attchFiles2 = new ArrayList<File>();
        attchFiles2.add(txtFile2);   attchFiles2.add(docFile2);
    
        
        //封裝單個郵件bean
        MailSendeBean mailSendeBean2 = new MailSendeBean( emailAddress2, subject2,  content2,attchFiles2);
        
        //封裝多個郵件bean
        List<MailSendeBean> mailList = new ArrayList<MailSendeBean>();
        mailList.add(mailSendeBean1); mailList.add(mailSendeBean2);
        
        // 傳送郵件
       String resultMessage =  mailSender.sendToManyUser(mailList);
       System.out.println("resultMessage = " + resultMessage);
        
	}	
	
	//單個郵件傳送
	private void sendToOneUser() throws Exception{
		//初始化郵件伺服器
		MailSender mailSender = this.createMailSender();
		
		//建立郵件bean
		String emailAddress = "[email protected]";  
        String subject = "郵件主題測試";  
        String content = "郵件內容測試"; 
        //附件
        File txtFile = new File("D:"+File.separator+ "emailTest" + File.separator + "testText.txt");
        File docFile = new File("D:"+File.separator+ "emailTest" + File.separator + "testDoc.doc");
        File excelFile = new File("D:"+File.separator+ "emailTest" + File.separator + "testExcel.xls");
        File photoFile = new File("D:"+File.separator+ "emailTest" + File.separator + "testPhoto.jpg");
        
        List<File> attchFiles = new ArrayList<File>();
        attchFiles.add(txtFile);   attchFiles.add(docFile);
        attchFiles.add(excelFile);   attchFiles.add(photoFile);
        
        //封裝郵件bean
        MailSendeBean mailSendeBean = new MailSendeBean( emailAddress, subject,  content,attchFiles);
        
        // 傳送郵件
       String resultMessage =  mailSender.sendToOneUser(mailSendeBean);
       System.out.println("resultMessage = " + resultMessage);
        
	}
	

	public static void main(String args[]) throws Exception{
		MailSenderDemo mailDemo = new MailSenderDemo();
		mailDemo.sendToOneUser(); // 測試單個郵件傳送
//		mailDemo.sendToManyUser(); // 測試多個郵件傳送
	}
	
}