java郵件發送(單人,多人,抄送,Excel附件)


  直接上代碼保存吧

  

package com.westvalley.ceiec.page.report.sendmail;

import weaver.email.EmailEncoder;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import javax.activation.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import crivia.db.i.DataSet;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;

/**郵件發送工具類
 * @author whh
 */
public class Email {
    
    Log log = LogFactory.getLog(this.getClass());
    
    //發件人地址
    private String mail_from;
    public void setMail_from(String mailFrom) {
        mail_from = mailFrom;
    }
    public String getMail_from() {
        return mail_from;
    }
    
    //發件人密碼
    private String password;
    public void setPassword(String password) {
        this.password = password;
    }
    public String getPassword() {
        return password;
    }
    
    //收件地址
    private String mail_to;
    public void setMail_to(String mailTo) {
        mail_to = mailTo;
    }
    public String getMail_to() {
        return mail_to;
    }
    
    //主題
    private String title;
    public void setTitle(String title) {
        this.title = title;
    }
    public String getTitle() {
        return title;
    }
    
    //內容
    private String message;
    public void setMessage(String message) {
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
    
    //發件人郵件服務器 如:ceiec-electric.com 191.0.0.6
    private String send_server;
    public void setSend_server(String sendServer) {
        send_server = sendServer;
    }
    public String getSend_server() {
        return send_server;
    }
    
    /** 單個發送 setMail_to(String mailTo)
     * @return 是否正確發送
     * @throws AddressException
     */
    public boolean SendMail()throws AddressException{
        try{
            int n = this.mail_from.indexOf('@');
            int m = this.mail_from.length();
            //取郵件的服務器
            String server = this.mail_from.substring(n+1, m);
            //建立郵件會話
            Properties pro = new Properties();
            pro.put("mail.smtp.host", "smtp."+server);
            pro.put("mail.smtp.auth", "true");
            Session sess = Session.getInstance(pro);
            sess.setDebug(true);
            //新建一個消息對象
            MimeMessage message = new MimeMessage(sess);
            //設置發件人
            InternetAddress from_address = new InternetAddress(this.mail_from);
            message.setFrom(from_address);
            //設置收件人
            InternetAddress to_address = new InternetAddress(this.mail_to);
            message.setRecipient(Message.RecipientType.TO, to_address);
            //設置主題
            message.setSubject(title);
            //設置內容
            message.setContent(this.message, "text/html;charset=UTF-8");
            //設置發送時間
            message.setSentDate(new Date());
            //發送郵件
            message.saveChanges(); //保存郵件信息
            //設置發送的格式            
            Transport transport = sess.getTransport("smtp");
            if(this.send_server == null){
                transport.connect("191.0.0.6", this.mail_from, password);
            }
            else{
                transport.connect(this.send_server, this.mail_from, password);
            }
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            log.info("向"+this.mail_to+"發送郵件成功");
            return true;
        }catch(Exception e){
            log.info("發送郵件失敗,原因可能是"+e.toString());
            return false;
        }
        
    }
    
    /**群發 
     * @param addresses 地址list
     * @return 
     * @throws AddressException
     */
    public boolean SendMail(List<String> addresses) throws AddressException{
        try{
            int n = this.mail_from.indexOf('@');
            int m = this.mail_from.length();
            //取郵件的服務器
            String server = this.mail_from.substring(n+1, m);
            //建立郵件會話
            Properties pro = new Properties();
            pro.put("mail.smtp.host", "smtp."+server);
            pro.put("mail.smtp.auth", "true");
            Session sess = Session.getInstance(pro);
            sess.setDebug(true);
            //新建一個消息對象
            MimeMessage message = new MimeMessage(sess);
            //設置發件人
            InternetAddress from_address = new InternetAddress(this.mail_from);
            message.setFrom(from_address);
            //設置收件人,多個
            final int num = addresses.size();
            InternetAddress to_address[] = new InternetAddress[num];
            for(int i=0; i<num; i++){
                to_address[i] = new InternetAddress(addresses.get(i));
            }
            message.setRecipients(Message.RecipientType.TO, to_address);
            //設置主題
            message.setSubject(title);
            //設置內容
            message.setContent(this.message, "text/html;charset=UTF-8");
            //設置發送時間
            message.setSentDate(new Date());
            //發送郵件
            message.saveChanges(); //保存郵件信息
            //設置發送的格式            
            Transport transport = sess.getTransport("smtp");
            if(this.send_server == null){
                transport.connect("191.0.0.6", this.mail_from, password);
            }
            else{
                transport.connect(this.send_server, this.mail_from, password);
            }
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            log.info("發送郵件成功");
            return true;
        }catch(Exception e){
            log.info("發送郵件失敗,原因可能是"+e.getMessage());
            return false;
        }
        
    }
    
    /** 多人發送並抄送 增加:2017-04-25 whh
     * @param addresses 收件郵箱(多個)
     * @param ccAddresses 抄送郵箱(多個)
     * @return
     * @throws AddressException
     */
    public boolean SendMail(List<String> addresses, List<String> ccAddresses) throws 
        AddressException{
        if(0==ccAddresses.size()){ //20170428 whh
            return SendMail(addresses);
        }
        try{
            int n = this.mail_from.indexOf('@');
            int m = this.mail_from.length();
            //取郵件的服務器
            String server = this.mail_from.substring(n+1, m);
            //建立郵件會話
            Properties pro = new Properties();
            pro.put("mail.smtp.host", "smtp."+server);
            pro.put("mail.smtp.auth", "true");
            Session sess = Session.getInstance(pro);
            sess.setDebug(true);
            //新建一個消息對象
            MimeMessage message = new MimeMessage(sess);
            //設置發件人
            InternetAddress from_address = new InternetAddress(this.mail_from);
            message.setFrom(from_address);
            //設置收件人,多個
            final int num = addresses.size();
            InternetAddress to_address[] = new InternetAddress[num];
            for(int i=0; i<num; i++){
                to_address[i] = new InternetAddress(addresses.get(i));
            }
            message.setRecipients(Message.RecipientType.TO, to_address);
            //設置抄送人
            final int ccSize = ccAddresses.size();
            if(ccSize > 0){
                InternetAddress cc_Address[] = new InternetAddress[ccSize];
                for(int i=0; i<ccSize; i++){
                    cc_Address[i] = new InternetAddress(ccAddresses.get(i));
                }
                message.setRecipients(Message.RecipientType.CC, cc_Address);
            }    
            
            //設置主題
            message.setSubject(title);
            //設置內容
            message.setContent(this.message, "text/html;charset=UTF-8");
            //設置發送時間
            message.setSentDate(new Date());
            //發送郵件
            message.saveChanges(); //保存郵件信息
            //設置發送的格式            
            Transport transport = sess.getTransport("smtp");
            if(this.send_server == null){
                transport.connect("191.0.0.6", this.mail_from, password);
            }
            else{
                transport.connect(this.send_server, this.mail_from, password);
            }
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            log.info("發送郵件成功");
            return true;
        }catch(Exception e){
            log.info("發送郵件失敗,原因可能是"+e.getMessage());
            return false;
        }
        
    }
    
    /** 多人發送並抄送 增加:2019-06-14 whh
     * @param addresses 收件郵箱(多個)
     * @param ccAddresses 抄送郵箱(多個)
     * @param is 附件
     * @return
     * @throws AddressException
     */
    public boolean SendMail(List<String> addresses, List<String> ccAddresses,
            HSSFWorkbook workBook,String workBookName) throws 
        AddressException{
        try{
            int n = this.mail_from.indexOf('@');
            int m = this.mail_from.length();
            //取郵件的服務器
            String server = this.mail_from.substring(n+1, m);
            //建立郵件會話
            Properties pro = new Properties();
            pro.put("mail.smtp.host", "smtp."+server);
            pro.put("mail.smtp.auth", "true");
            Session sess = Session.getInstance(pro);
            sess.setDebug(true);
            //新建一個消息對象
            MimeMessage message = new MimeMessage(sess);
            //設置發件人
            InternetAddress from_address = new InternetAddress(this.mail_from);
            message.setFrom(from_address);
            //設置收件人,多個
            final int num = addresses.size();
            InternetAddress to_address[] = new InternetAddress[num];
            for(int i=0; i<num; i++){
                to_address[i] = new InternetAddress(addresses.get(i));
            }
            message.setRecipients(Message.RecipientType.TO, to_address);
            //設置抄送人
            final int ccSize = ccAddresses.size();
            if(ccSize > 0){
                InternetAddress cc_Address[] = new InternetAddress[ccSize];
                for(int i=0; i<ccSize; i++){
                    cc_Address[i] = new InternetAddress(ccAddresses.get(i));
                }
                message.setRecipients(Message.RecipientType.CC, cc_Address);
            }    
            
            //附件
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workBook.write(baos);
            baos.flush();
            byte[] bt = baos.toByteArray();
            InputStream is = new ByteArrayInputStream(bt, 0, bt.length);
            baos.close();
            
            /*添加正文內容*/  
            Multipart multipart = new MimeMultipart();  
            BodyPart contentPart = new MimeBodyPart();  
//            contentPart.setText(this.message);  
//            contentPart.setHeader("Content-Type", "text/html;charset=UTF-8"); 
            contentPart.setContent(this.message, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);  
              
            /*添加附件*/  
            MimeBodyPart fileBody = new MimeBodyPart();  
            DataSource source = new ByteArrayDataSource(is, "application/msexcel"); 
            fileBody.setDataHandler(new DataHandler(source));  
            // 中文亂碼問題
            fileBody.setFileName(MimeUtility.encodeText(workBookName+".xls"));  
            multipart.addBodyPart(fileBody);
            
            //設置主題
            message.setSubject(title);
            //設置內容
            message.setContent(multipart);
            //設置發送時間
            message.setSentDate(new Date());
            //發送郵件
            message.saveChanges(); //保存郵件信息
            //設置發送的格式            
            Transport transport = sess.getTransport("smtp");
            if(this.send_server == null){
                transport.connect("191.0.0.6", this.mail_from, password);
            }
            else{
                transport.connect(this.send_server, this.mail_from, password);
            }
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            log.info("發送郵件成功");
            return true;
        }catch(Exception e){
            log.info("發送郵件失敗,原因可能是"+e.getMessage());
            return false;
        }
        
    }
    
    /**郵箱初始化,發件人郵箱、密碼及服務器信息的獲取
     * @return 正確獲取時返回Email對象,否則為null
     */
    public static Email intiEmail(){
//        Log log = LogFactory.getLog(this.getClass());
        Email email = new Email();
        //獲取系統的郵箱信息
        DataSet data = SQL.select(SQL.sql_Array(" select defmailpassword" +
                ",defmailserver,defmailfrom from SystemSet "));
        if(data.next()){
            //發件人郵箱地址
            email.setMail_from(data.get("defmailfrom")); 
            //獲取並解析郵箱密碼
            email.setPassword(EmailEncoder.DecoderPassword(data.get("defmailpassword")));
//            log.info("Password:"+EmailEncoder.DecoderPassword(data.get("defmailpassword")));
            //服務器信息
            email.setSend_server(data.get("defmailserver"));
        }
        if(email.getMail_from().equals("")||
                email.getPassword().equals("")||
                email.getSend_server().equals("")){
//            log.info("發送人郵箱錯誤");
//            log.info("From:"+email.getMail_from()+"Password:"+
//                    email.getPassword()+"Server:"+email.getSend_server());    
            return null;
        }
        return email;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM