java 郵件 接收與發送


...

package com.e6soft;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.BodyTerm;
import javax.mail.search.SearchTerm;
import javax.mail.Address;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import org.quartz.impl.jdbcjobstore.DBSemaphore;

import com.e6soft.base.service.JService;
import com.sun.mail.imap.IMAPMessage;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;



public class MainTest extends JService{

    static String HOST = "smtp.163.com"; // smtp服務器
    static String FROM = "****@163.com"; // 發件人地址
    
    //static String TO = "******@qq.com"; // 收件人地址
    //static String AFFIX = "E:\\安裝手冊-6.3.5.doc"; // 附件地址
    //static String AFFIXNAME = "安裝手冊-6.3.5.doc"; // 附件名稱
    
    static String USER = "******"; // 用戶名
    static String PWD = "**********"; // 163的授權碼
    
    //static String SUBJECT = "您願望單中的 2 件物品正在促銷!"; // 郵件標題
    //static String[] TOS = TO.split(",");
    
    public static void main(String[] args) {
        MainTest mainTest=new MainTest();
        //mainTest.send("123456@qq.com","Your registration is complete!","注冊驗證您好 123456@qq.com!歡迎注冊碼雲,請將驗證碼填寫到注冊頁面。驗證碼:******","");
     //(以上是) 發送的郵箱,標題,內容,
        //mainTest.send("請盡快配合申請工作");
        mainTest.getEmailList();
    }

    /* 發件人 -> MUA -> MTA -> MTA -> 若干個MTA -> MDA <- MUA <- 收件人
          本質上就是:
                編寫MUA把郵件發到MTA;
                編寫MUA從MDA上收郵件。
        發郵件時,MUA和MTA使用的協議就是SMTP:Simple Mail Transfer Protocol,后面的MTA到另一個MTA也是用SMTP協議。
        收郵件時,MUA和MDA使用的協議有兩種:POP:Post Office Protocol
        
        在MyEclipse中,會自動給web項目導入javax.mail包中的類,但是不全(其實是只有接口,而沒有接口的實現類),所以只靠MyEclipse中的類是不能運行java mail項目的,但是如果這時你再去自行導入mail.jar時,就會出現沖突。
        
        java mail中主要類:javax.mail.Session、javax.mail.internet.MimeMessage、javax.mail.Transport。
            Session:表示會話,即客戶端與郵件服務器之間的會話!想獲得會話需要給出賬戶和密碼,當然還要給出服務器名稱。在郵件服務中的Session對象,就相當於連接數據庫時的Connection對象。            
            MimeMessage:表示郵件類,它是Message的子類。它包含郵件的主題(標題)、內容,收件人地址、發件人地址,還可以設置抄送和暗送,甚至還可以設置附件。            
            Transport:用來發送郵件。它是發送器!
     */
    /* 以下是參考 // 接收
    public static void s() throws IOException{
        System.out.print("請輸入用戶名:");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String userName = in.readLine();
        System.out.print("請輸入密碼:");
        String password = in.readLine();
        BASE64Encoder encoder = new BASE64Encoder();
        System.out.println("編碼后的用戶名為:" + encoder.encode(userName.getBytes()));
        System.out.println("編碼后的密碼為:" + encoder.encode(password.getBytes()));
        
        BASE64Decoder decoder = new BASE64Decoder();
        //郵件主題的Base64編碼
        String emailSubject = "=?GBK?B?08q8/rLiytQ=?=";
        //郵件文本內容的Base64編碼
        String emailPlainContent = "vPK1pbXE08q8/reiy82y4srUo6E=";
        //帶html標簽和郵件內容的Base64編碼
        String emailHtmlContent = "PFA+vPK1pbXE08q8/reiy82y4srUo6E8L1A+";
        //將使用Base64編碼過后的文本內容再使用Base64來解碼
        emailSubject = new String(decoder.decodeBuffer(emailSubject),"GBK");
        emailPlainContent = new String(decoder.decodeBuffer(emailPlainContent),"GBK");
        emailHtmlContent = new String(decoder.decodeBuffer(emailHtmlContent),"GBK");
        System.out.println("郵件標題:"+emailSubject);
        System.out.println("郵件內容:"+emailPlainContent);
        System.out.println("帶html標簽的郵件內容:"+emailHtmlContent);
    }
    // 接收
    public static void ss() throws Exception{
        //收件人地址
        String recipientAddress = "xxx@163.com";
        //收件人賬戶名
        String recipientAccount = "xxx";
        //收件人賬戶密碼
        String recipientPassword = "xxx";
        
        //1、連接郵件服務器的參數配置
        Properties props = new Properties();
        //設置傳輸協議
        props.setProperty("mail.store.protocol", "pop3");
        //設置收件人的POP3服務器
        props.setProperty("mail.pop3.host", "pop3.163.com");
        //2、創建定義整個應用程序所需的環境信息的 Session 對象
        Session session = Session.getInstance(props);
        //設置調試信息在控制台打印出來
        //session.setDebug(true);
         
        Store store = session.getStore("pop3");
        //連接收件人POP3服務器
        store.connect("pop3.163.com", recipientAccount, recipientPassword);
        //獲得用戶的郵件賬戶,注意通過pop3協議獲取某個郵件夾的名稱只能為inbox
        Folder folder = store.getFolder("inbox");
        //設置對郵件賬戶的訪問權限
        folder.open(Folder.READ_WRITE);
         
        //得到郵件賬戶的所有郵件信息
        Message [] messages = folder.getMessages();
        for(int i = 0 ; i < messages.length ; i++){
            //獲得郵件主題
            String subject = messages[i].getSubject();
            //獲得郵件發件人
            Address[] from = messages[i].getFrom();
            //獲取郵件內容(包含郵件內容的html代碼)
            String content = (String) messages[i].getContent();
        }
         
        //關閉郵件夾對象
        
        folder.close(false);
        
        //關閉連接對象
        store.close();
    }
    */
    
    
    /**
     * 發送郵件 
     *     sjrdz 收件人地址
     *     bt 標題
     *     context 內容
     * @param host
     * @param user
     * @param pwd
     */
    public static void send(String sjrdz,String bt,String context,String fjId) {
        MainTest MainTest=new MainTest();
        String []TOS=sjrdz.split(",");
        Properties props = new Properties(); // Session 對象利用了java.util.Properties對象獲得了郵件服務器、用戶名、密碼信息  和整個應用程序都要使用到的 共享信息
        props.put("mail.smtp.host", HOST);//設置發送郵件的郵件服務器的屬性(這里使用網易的smtp服務器)
        props.put("mail.smtp.auth", "true");  //需要經過授權,也就是有戶名和密碼的校驗,這樣才能通過驗證(一定要有這一條)
        Session session = Session.getDefaultInstance(props);//用props對象構建一個session
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);//用session為參數定義消息對象
        try {
            message.setFrom(new InternetAddress(FROM));// 加載發件人地址
            InternetAddress[] sendTo = new InternetAddress[TOS.length]; // 加載收件人地址
            for (int i = 0; i < TOS.length; i++) {  
                sendTo[i] = new InternetAddress(TOS[i]);  
            }
            message.addRecipients(Message.RecipientType.TO,sendTo);
            message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(FROM));//設置在發送給收信人之前給自己(發送方)抄送一份,不然會被當成垃圾郵件,報554錯
            message.setSubject(bt);//加載標題
            Multipart multipart = new MimeMultipart();//向multipart對象中添加郵件的各個部分內容,包括文本內容和附件
            BodyPart contentPart = new MimeBodyPart();//設置郵件的文本內容
            contentPart.setText(context);
            multipart.addBodyPart(contentPart);
            
            
            if(!fjId.isEmpty()){//添加附件
                String sqlString="select t.file_extend,t.file_info_id,t.file_filename,t.file_url from T_P_FILE_INFO t where t.file_index='"+fjId+"' ";
                List<Map<String, Object>> list=MainTest.dBSelect(sqlString);
                 for(int i=0;i<list.size();i++){
                     BodyPart messageBodyPart = new MimeBodyPart();
                     String AFFIX=System.getProperty("catalina.home")+"/webapps/webdav/"+list.get(i).get("file_info_id")+"."+list.get(i).get("file_extend");
                     String AFFIXNAME=list.get(i).get("file_filename").toString();
                     DataSource source = new FileDataSource(AFFIX);
                     messageBodyPart.setDataHandler(new DataHandler(source));//添加附件的內容
                     sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();//添加附件的標題
                     messageBodyPart.setFileName("=?GBK?B?"+ enc.encode(AFFIXNAME.getBytes()) + "?=");
                     multipart.addBodyPart(messageBodyPart);
                 }
                 
            }
            message.setContent(multipart);//將multipart對象放到message中
            message.saveChanges(); //保存郵件
            Transport transport = session.getTransport("smtp");//發送郵件
            transport.connect(HOST, USER, PWD);//連接服務器的郵箱
            transport.sendMessage(message, message.getAllRecipients());//把郵件發送出去
            transport.close();//關閉連接
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    //獲取郵件列表
    public void getEmailList(){
        Properties props = new Properties(); //1、連接郵件服務器的參數配置
        
        props.put("mail.store.protocol", "imap"); //設置傳輸協議
        props.put("mail.imap.host", "imap.163.com"); //設置收件人的POP3服務器
        //props.put("mail.imap.port", "143");
        props.put("mail.imap.auth.plain.disable","true");
        Session session = Session.getDefaultInstance(props); //2、創建定義整個應用程序所需的環境信息的 Session 對象
        Store store;
        try {
            store = session.getStore("imap"); //連接收件人POP3服務器
            store.connect("imap.163.com",USER, PWD);
            Folder folder = store.getFolder("INBOX"); //獲得用戶的郵件賬戶,注意通過pop3協議獲取某個郵件夾的名稱只能為inbox
            folder.open(Folder.READ_WRITE); //設置對郵件賬戶的訪問權限
            //SearchTerm search= new BodyTerm("test");  
            //Message[] messages = folder.search(search);  //得到郵件賬戶的所有郵件信息
            Message[] messages = folder.getMessages();
            for (int i = 0 ; i < messages.length; i++){
                Message msg = messages[i];
                                
                InternetAddress address =  (InternetAddress) msg.getFrom()[0];
                System.out.println(" [ #" + i + " ] ");
                System.out.println( "Subject : " + msg.getSubject()); // 回復的標題
                    //Subject : 回復:Your registration is complete!
                System.out.println("From : " + address.getPersonal() + "<" + address.getAddress() + ">"); // 回復人的名稱和郵箱
                    //From : " Follow your heart "<935220462@qq.com>
                System.out.println("ContentType : " + msg.getContentType());  //內容類型
                    //ContentType : multipart/alternative; 
                    //    boundary="----=_NextPart_5CA330D9_0A968A68_5C0E2915"
                //Message表示一個郵件,msg.getContent()返回一個Multipart對象。一個Multipart對象包含一個或多個BodyPart對象,來組成郵件的正文部分(包括附件)。
                System.out.println("Content Detail : " + msg.getContent().toString()); // 內容細節
                    //Content Detail : javax.mail.internet.MimeMultipart@12bc6874
                System.out.println("時間 : " + msg.getSentDate()); // 日期和時間 
                
                if(msg.isMimeType("multipart/*")){ 
                    Multipart mp = (Multipart)msg.getContent();
                    int bodynum = mp.getCount();
                    for(int j=0; j<bodynum; j++){
                        if(mp.getBodyPart(j).isMimeType("text/html")){
                            String content = (String)mp.getBodyPart(j).getContent();
                            System.out.print("郵件內容:"+content);
                        }
                    }
                }else{  
                    System.out.println("不支持的郵件類型!");  
                }  
            }
            folder.close(false);
            store.close();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
    
    /**
     * 解析綜合數據
     * @param part
     * @throws Exception
     */
    private static void getAllMultipart(Part part) throws Exception{
     String contentType = part.getContentType();
     int index = contentType.indexOf("name");
     boolean conName = false;
     if(index!=-1){
      conName=true;
     }
     //判斷part類型
     if(part.isMimeType("text/plain") && ! conName) {
      System.out.println((String) part.getContent());
     }else if (part.isMimeType("text/html") && ! conName) {
      System.out.println((String) part.getContent());
     }else if (part.isMimeType("multipart/*")) {
      Multipart multipart = (Multipart) part.getContent();
      int counts = multipart.getCount();
      for (int i = 0; i < counts; i++) {
       //遞歸獲取數據
       getAllMultipart(multipart.getBodyPart(i));
       //附件可能是截圖或上傳的(圖片或其他數據)
       if (multipart.getBodyPart(i).getDisposition() != null) {
        //附件為截圖
        if (multipart.getBodyPart(i).isMimeType("image/*")) {
         InputStream is = multipart.getBodyPart(i)
           .getInputStream();
         String name = multipart.getBodyPart(i).getFileName();
         String fileName;
         //截圖圖片
         if(name.startsWith("=?")){
          fileName = name.substring(name.lastIndexOf(".") - 1,name.lastIndexOf("?="));
         }else{
          //上傳圖片
          fileName = name;
         }
        
         FileOutputStream fos = new FileOutputStream("D:\\"
           + fileName);
         int len = 0;
         byte[] bys = new byte[1024];
         while ((len = is.read(bys)) != -1) {
          fos.write(bys,0,len);
         }
         fos.close();
        } else {
         //其他附件
         InputStream is = multipart.getBodyPart(i)
           .getInputStream();
         String name = multipart.getBodyPart(i).getFileName();
         FileOutputStream fos = new FileOutputStream("D:\\"
           + name);
         int len = 0;
         byte[] bys = new byte[1024];
         while ((len = is.read(bys)) != -1) {
          fos.write(bys,0,len);
         }
         fos.close();
        }
       }
      }
     }else if (part.isMimeType("message/rfc822")) {
      getAllMultipart((Part) part.getContent());
     } 
    }
    
    /**
     * 解析附件內容
     * @param part
     * @throws Exception
     */
    private static void getAttachmentMultipart(Part part) throws Exception{
     if(part.isMimeType("multipart/*")){
      Multipart multipart = (Multipart) part.getContent();
      int count = multipart.getCount();
      for (int i = 0; i < count; i++) {
       BodyPart bodyPart = multipart.getBodyPart(i);
       if(bodyPart.getDisposition()!=null){
        InputStream is = bodyPart.getInputStream();
        FileOutputStream fos=new FileOutputStream("路徑+文件名");
        int len=0;
        byte[] bys=new byte[1024];
        while((len=is.read(bys))!=-1){
         fos.write(bys, 0, len);
        }
        fos.close();
       }
      }
     }
     
    }
    /**
     * 解析圖片內容
     * @param part
     * @throws Exception
     */
    private static void getPicMultipart(Part part) throws Exception{
     if(part.isMimeType("multipart/*")){
      Multipart multipart = (Multipart) part.getContent();
      int count = multipart.getCount();
      for (int i = 0; i < count; i++) {
       BodyPart bodyPart = multipart.getBodyPart(i);
       if(bodyPart.isMimeType("image/*")){
        InputStream is = bodyPart.getInputStream();
        FileOutputStream fos=new FileOutputStream("路徑+文件名");
        int len=0;
        byte[] bys=new byte[1024];
        while((len=is.read(bys))!=-1){
         fos.write(bys, 0, len);
        }
        fos.close();
       }
      }
     }
    }
    /**
     * 解析文本內容
     * @param part
     * @throws Exception
     */
    private static void getTextMultipart(Part part) throws Exception{
     if(part.isMimeType("text/html")){
      String content = (String) part.getContent();
      System.out.println(content);
     }else if(part.isMimeType("text/plain")){
      String content = (String) part.getContent();
      System.out.println(content);
     }

    }

}

 


免責聲明!

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



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