javaemail功能齊全的發送郵件類【能上傳附件哦】

從網上找了一個些資料,再原本的基礎上增加的發送附件功能,附件上傳的最大容量 默認20M

需要導入一個包mail.jar,隨便下一個吧

package common; 
/** 
* 發送郵件需要使用的基本信息 
*/  
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;  
public class MailSenderInfo {  
    // 發送郵件的服務器的IP和端口  
    private String mailServerHost;  
    private String mailServerPort = "25";  
    // 郵件發送者的地址  
    private String fromAddress;  
    // 郵件接收者的地址  
    //private String toAddress;
    private List<String> toAddress;
    // 郵件抄送者的地址
    private List<String> ccAddress;
    // 郵件暗送者的地址
    private List<String> bccAddress;
    // 登陸郵件發送服務器的用戶名和密碼  
    private String userName;  
    private String password;  
    // 是否需要身份驗證  
    private boolean validate = true;  
    // 郵件主題  
    private String subject;  
    // 郵件的文本內容  
    private String content;  
    // 郵件附件的文件名  
    private String[] attachFileNames;
    //郵件附件路徑
    private List<String> filePaths;
    //是否打印郵件發送調試信息
    private boolean debug;
    //附件上傳的最大容量 默認20M
    public static final long fileMaxSize = 20971520;
   
    public MailSenderInfo(){
     this.debug = false;
     this.toAddress = new ArrayList<String>();//收件人郵箱
     this.ccAddress = new ArrayList<String>();//抄送人郵箱
     this.bccAddress = new ArrayList<String>();//暗送人郵箱
     this.filePaths =new ArrayList<String>();//附件
    }
    /** 
      * 獲得郵件會話屬性 
      */  
    public Properties getProperties(){  
      Properties p = new Properties();  
      p.put("mail.smtp.host", this.mailServerHost);  
      p.put("mail.smtp.port", this.mailServerPort);  
      p.put("mail.smtp.auth", validate ? "true" : "false");  
      return p;  
    }  
//    public String getToAddress() {  
//     return this.toAddress;  
// }  
// public void setToAddress(String toAddress) {  
//     this.toAddress = toAddress;  
// } 
    public String getMailServerHost() {  
      return mailServerHost;  
    }  
    public void setMailServerHost(String mailServerHost) {  
      this.mailServerHost = mailServerHost;  
    } 
    public String getMailServerPort() {  
      return mailServerPort;  
    } 
    public void setMailServerPort(String mailServerPort) {  
      this.mailServerPort = mailServerPort;  
    } 
    public boolean isValidate() {  
      return validate;  
    } 
    public void setValidate(boolean validate) {  
      this.validate = validate;  
    } 
    public String[] getAttachFileNames() {  
      return attachFileNames;  
    } 
    public void setAttachFileNames(String[] fileNames) {  
      this.attachFileNames = fileNames;  
    } 
    public String getFromAddress() {  
      return fromAddress;  
    }  
    public void setFromAddress(String fromAddress) {  
      this.fromAddress = fromAddress;  
    } 
    public String getPassword() {  
      return password;  
    } 
    public void setPassword(String password) {  
      this.password = password;  
    } 
    public String getUserName() {  
      return userName;  
    } 
    public void setUserName(String userName) {  
      this.userName = userName;  
    } 
    public String getSubject() {  
      return subject;  
    } 
    public void setSubject(String subject) {  
      this.subject = subject;  
    } 
    public String getContent() {  
      return content;  
    } 
    public void setContent(String textContent) {  
      this.content = textContent;  
    }
 public List<String> getToAddress() {
  return toAddress;
 }
 public void setToAddress(List<String> toAddress) {
  this.toAddress = toAddress;
 }
 public List<String> getCcAddress() {
  return ccAddress;
 }
 public void setCcAddress(List<String> ccAddress) {
  this.ccAddress = ccAddress;
 }
 public List<String> getBccAddress() {
  return bccAddress;
 }
 public void setBccAddress(List<String> bccAddress) {
  this.bccAddress = bccAddress;
 }  
 public void addToAddress(String mailAddress) {
        this.toAddress.add(mailAddress);
    }
    public void addCcAddress(String mailAddress) {
        this.ccAddress.add(mailAddress);
    }
    public void addBccAddress(String mailAddress) {
        this.bccAddress.add(mailAddress);
    }
 public boolean isDebug() {
  return debug;
 }
 public void setDebug(boolean debug) {
  this.debug = debug;
 }
 public List<String> getFilePaths() {
  return filePaths;
 }
 public void setFilePaths(List<String> filePaths) {
  this.filePaths = filePaths;
 }
 public void addAttachment(String filePath) {
        this.filePaths.add(filePath);
    }
}  

 

package common; 
 
import java.io.File;
import java.util.ArrayList;
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.Address;  
import javax.mail.Authenticator;
import javax.mail.BodyPart;  
import javax.mail.Message;  
import javax.mail.MessagingException;  
import javax.mail.Multipart;  
import javax.mail.PasswordAuthentication;
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.MimeMultipart;  
import javax.mail.internet.MimeUtility;

/** 
* 郵件發送器 
*/  
public class MailSender  { 
 
   //驗證郵件對象
   private class MyAuthenticator extends Authenticator{ 
     String userName=null; 
     String password=null; 
     public MyAuthenticator(){ 
     } 
     public MyAuthenticator(String username, String password) {  
         this.userName = username;  
         this.password = password;  
     }  
     protected PasswordAuthentication getPasswordAuthentication(){ 
         return new PasswordAuthentication(userName, password); 
     } 
 }
 
 /** 
   * 以文本格式發送郵件 
   * @param mailInfo 待發送的郵件的信息 
   */  
    public static boolean sendTextMail(MailSenderInfo mailInfo) {  
      // 判斷是否需要身份認證  
      MyAuthenticator authenticator = null;  
      Properties pro = mailInfo.getProperties(); 
      if (mailInfo.isValidate()) {  
      // 如果需要身份認證,則創建一個密碼驗證器  
        authenticator = (new MailSender()).new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());  
      } 
      // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session  
      Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
      //是否打印郵件會話調試信息
      sendMailSession.setDebug(mailInfo.isDebug());
      try {  
      // 根據session創建一個郵件消息  
      Message mailMessage = new MimeMessage(sendMailSession);  
      // 創建郵件發送者地址  
      Address from = new InternetAddress(mailInfo.getFromAddress());  
      // 設置郵件消息的發送者  
      mailMessage.setFrom(from);  
      // 創建郵件的接收者地址,並設置到郵件消息中  
      //Address to = new InternetAddress(mailInfo.getToAddress());  
      Address[] tos = getAddress(mailInfo.getToAddress());
      //mailMessage.setRecipient(Message.RecipientType.TO,to);//設置單個收件人
      mailMessage.setRecipients(Message.RecipientType.TO,tos);//設置多個收件人
      //創建郵件的抄送者地址,並設置到郵件消息中
      Address[] ccs = getAddress(mailInfo.getCcAddress());
      mailMessage.setRecipients(Message.RecipientType.CC,ccs);
      //創建郵件的暗送者地址,並設置到郵件消息中
      Address[] bccs = getAddress(mailInfo.getBccAddress());
      mailMessage.setRecipients(Message.RecipientType.BCC,bccs);
      // 設置郵件消息的主題  
      mailMessage.setSubject(mailInfo.getSubject());  
      // 設置郵件消息發送的時間  
      mailMessage.setSentDate(new Date());
      // 設置郵件消息的主要內容  
      //String mailContent = mailInfo.getContent();  
      //mailMessage.setText(mailContent);
      // 向multipart對象中添加郵件的各個部分內容,包括文本內容和附件
      Multipart mainPart = new MimeMultipart();        
      //設置郵件的文本內容
      BodyPart contentPart = new MimeBodyPart();
      contentPart.setText(mailInfo.getContent());
      mainPart.addBodyPart(contentPart);
      // 添加附件
      if(!addFileAffix(mailMessage,mainPart,mailInfo.getFilePaths())){
       System.out.println("郵件發送失敗!");
       return false;
      }
      //將multipart對象放到message中
      mailMessage.setContent(mainPart);
      // 發送郵件  
      Transport.send(mailMessage); 
      return true;  
      } catch (MessagingException ex) {  
          ex.printStackTrace();  
      }  
      return false;  
    }  
     
    /** 
      * 以HTML格式發送郵件 
      * @param mailInfo 待發送的郵件信息 
      */  
    public static boolean sendHtmlMail(MailSenderInfo mailInfo){  
      // 判斷是否需要身份認證  
      MyAuthenticator authenticator = null; 
      Properties pro = mailInfo.getProperties(); 
      //如果需要身份認證,則創建一個密碼驗證器   
      if (mailInfo.isValidate()) {  
        authenticator =(new MailSender()).new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); 
      }  
      // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session  
      Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
      //是否打印郵件會話調試信息
      sendMailSession.setDebug(mailInfo.isDebug());
      try {  
       // 根據session創建一個郵件消息  
       Message mailMessage = new MimeMessage(sendMailSession);  
       // 創建郵件發送者地址  
       Address from = new InternetAddress(mailInfo.getFromAddress());  
       // 設置郵件消息的發送者  
       mailMessage.setFrom(from); 
       // 創建郵件的接收者地址,並設置到郵件消息中
       Address[] tos = getAddress(mailInfo.getToAddress());
       // Message.RecipientType.TO屬性表示接收者的類型爲TO  
       //mailMessage.setRecipient(Message.RecipientType.TO,to);
       mailMessage.setRecipients(Message.RecipientType.TO,tos);
       //創建郵件的抄送者地址,並設置到郵件消息中
       Address[] ccs = getAddress(mailInfo.getCcAddress());
       mailMessage.setRecipients(Message.RecipientType.CC,ccs);
       //創建郵件的暗送者地址,並設置到郵件消息中
       Address[] bccs = getAddress(mailInfo.getBccAddress());
       mailMessage.setRecipients(Message.RecipientType.BCC,bccs);
       // 設置郵件消息的主題  
       mailMessage.setSubject(mailInfo.getSubject());  
       // 設置郵件消息發送的時間  
       mailMessage.setSentDate(new Date());  
       // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象  
       Multipart mainPart = new MimeMultipart();  
       // 創建一個包含HTML內容的MimeBodyPart  
       BodyPart html = new MimeBodyPart();  
       // 設置HTML內容  
       html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");  
       mainPart.addBodyPart(html);  
       // 將MiniMultipart對象設置爲郵件內容  
       mailMessage.setContent(mainPart); 
       // 添加附件
       if(!addFileAffix(mailMessage,mainPart,mailInfo.getFilePaths())){
        System.out.println("郵件發送失敗!");
        return false;
       }
       // 發送郵件  
       Transport.send(mailMessage);  
       return true;  
      } catch (Exception ex) {  
          ex.printStackTrace();  
      }  
      return false;  
    }
   
    /**
     * 創建郵件的接收者地址
     * @author sd(chenfang)
     * @returnType Address[] 收件人郵箱地址
     * @param toAddress 收件人郵箱地址
     * @throws Exception
     */
    private static Address[] getAddress(List<String> toAddress){  
       List<Address> to = new ArrayList<Address>();
       try {
        for (int i=0; toAddress !=null && i<toAddress.size();i++) {
    String toMail =  toAddress.get(i);//獲取收件人郵箱地址
    if(toMail !=null && !"".equals(toMail)){
     to.add(new InternetAddress(toMail));//創建接收者地址
    }
     }
       } catch (AddressException e) {
    e.printStackTrace();
    }finally{
     return (Address[])to.toArray(new Address[to.size()]);
    }
    }
   
    /** 
     * 增加發送附件  
     * @param filenames 附件絕對路徑集
     * @return 
     */ 
    private static boolean addFileAffix(Message mailMessage,Multipart mainPart,List<String> filenames) {  
        boolean flavg=true;
     for (int i = 0; filenames !=null && i < filenames.size(); i ++) {
         String filename=filenames.get(i);
         if(filename != null && !"".equals(filename)){
          flavg = addFileAffix(mailMessage,mainPart,filename);
          if(!flavg){break;}
         }
  }
     return flavg;  
    }
   
    /** 
     * 增加發送附件  
     * @param filename 附件絕對路徑
     * @return 
     */ 
    private static boolean addFileAffix(Message mailMessage,Multipart mainPart,String filePath) {  
        System.out.println("增加郵件附件:" + filePath);  
        try {  
           //添加附件
       BodyPart messageBodyPart = new MimeBodyPart();
       File file = new File(filePath);
       if(file !=null && file.length() > MailSenderInfo.fileMaxSize){
         System.err.println("郵件附件名字爲" + file.getName() + "的文件大小超出允許容量範圍[最大附件文件大小爲"+ Constant.MAIL_FILE_SIZE +"B]");
         return false;
       }else if(file !=null){
        DataSource source = new FileDataSource(file);
        //添加附件的內容
        messageBodyPart.setDataHandler(new DataHandler(source));
        //設置附件的名字(可以防止郵件自動打開文件)
        String filename=file.getName();
        //附件名字轉碼
        //第一種方式 BASE64Encoder encode 轉碼
        //這裏很重要,通過下面的Base64編碼的轉換可以保證你的中文附件標題名在發送時不會變成亂碼
            //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
            //messageBodyPart.setFileName("=?GBK?B?"+enc.encode(filename.getBytes())+"?=");
        //第二中方式 MimeUtility encodeText 轉碼
        messageBodyPart.setFileName(MimeUtility.encodeText(filename));
        //添加附件
        mainPart.addBodyPart(messageBodyPart);
        //將multipart對象放到message中
        mailMessage.setContent(mainPart, "file");
        //保存郵件
            // message.saveChanges();
       }
        } catch (Exception e) {  
           System.err.println("增加郵件附件:" + filePath + "發生錯誤!" + e);  
           return false;  
        }  
        System.out.println("增加郵件附件成功!" );  
        return true;  
    }
   
    /**
     * 羣發郵件信息[收件人多個] 以HTML格式發送
     * @author sd(chenfang)
     * @dateTime 2012-7-10上午11:13:14
     * @returnType void
     * @param toMail -收件人地址[至少一個,否則發送失敗拋異常]
     * @param ccMail -抄送人地址
     * @param bccMail -暗送人地址
     * @param subject -郵件主題
     * @param content -郵件內容
     * @param filePaths -郵件附件
     */
    public static void batchSendMails(List<String> toMail,List<String> ccMail,List<String> bccMail,String subject,String content,List<String> filePaths)throws Exception{
     try{
            MailSenderInfo mail = new MailSenderInfo();
            mail.setMailServerHost("smtp.163.com"); // 郵件服務器地址
            mail.setUserName("[email protected]"); // 用戶名
            mail.setPassword("**********"); // 密碼
            mail.setFromAddress([email protected]); // 發件人郵箱
            /**設置收件人郵箱**/
            mail.setToAddress(toMail);
            /**設置抄送人郵箱**/
            mail.setCcAddress(ccMail);
            /**設置暗送人郵箱**/
            mail.setBccAddress(bccMail);
            /**郵件主題**/
            mail.setSubject(subject);
            /**郵件內容**/
            mail.setContent(content);
            /**設置郵件附件**/
            mail.setFilePaths(filePaths);
           
            MailSender.sendHtmlMail(mail);//發送HTML
     }catch (Exception e) {
      e.printStackTrace();
      throw new Exception("Exception:"+e.getMessage());
     }
    }
   
   
    public static void main(String[] args){ 
        //這個類主要是設置郵件 
      MailSenderInfo mailInfo = new MailSenderInfo();  
      mailInfo.setMailServerHost("smtp.163.com");   //主機
      //mailInfo.setMailServerPort("25");   //端口
      mailInfo.setValidate(true);   //登陸是否驗證
      mailInfo.setUserName([email protected]”);   //用戶名
      mailInfo.setPassword(“*********”);//密碼  
      mailInfo.setFromAddress(“”); //發件人郵箱
      mailInfo.addToAddress("[email protected]");//收件人郵箱1
      mailInfo.addToAddress("[email protected]");//收件人郵箱2
      mailInfo.addCcAddress("[email protected]");//抄送人郵箱1
      mailInfo.addCcAddress("[email protected]");//抄送人郵箱2
      mailInfo.addBccAddress("[email protected]");//暗送人郵箱1
      mailInfo.addBccAddress("[email protected]");//暗送人郵箱2
     
      mailInfo.setSubject("設置郵箱主題");   //郵件主題
      mailInfo.setContent("<b>設置郵箱內容</b> <br> http://www.baidu.com");//內容
      //mailInfo.addAttachment("C:/Users/sd/Desktop/工具.xlsx"); //附件1
      //mailInfo.addAttachment("C:/Users/sd/Desktop/帶附件的郵件發送.doc"); //附件2
      mailInfo.setFilePaths(null);
      System.out.println("郵件發送開始!"+(new Date().toLocaleString()));
      //這個類主要來發送郵件 
      //MailSender sms = new MailSender(); 
        // System.out.println("郵件發送成功是否!"+MailSender.sendTextMail(mailInfo));//發送文體格式  
         System.out.println("郵件發送成功是否!"+MailSender.sendHtmlMail(mailInfo));//發送html格式 

         System.out.println("郵件發送結束!"+(new Date().toLocaleString()));
   }
   
}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章