java email 邮件接收

package org.email.send;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.mail.Authenticator;
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.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.pop3.POP3Folder;

public class ReceiveEMailMessage{

        
    private String userName;

    private String password;

    // 邮箱服务器
    private String serverName;

    // 服务器端口
    private String serverPort;

    // 传输类型
    private String transportType;

    private String protocol;
    //是否验证
    private Boolean isAuth;
    
    private int timeout;
    
    private static Properties props;
    
    private String dateformate = "yy-MM-dd HH:mm";
    
    private String saveAttchPath="D:\\testEmail";
    

    
    public void init() {
        this.serverName = "pop3.longshine.com";
        this.serverPort = "110";
        this.protocol = "pop3";
        this.userName = "diguangming@longshine.com";
        this.password = "Longshine#1";
        this.isAuth = true;
        this.timeout = 600000;
        this.transportType = "smtp";
        
        props = new Properties();
        props.put("mail.transport.protocal", transportType);
        props.put("mail.store.protocol", protocol);
        props.put("mail.stmp.timeout", timeout);
        props.put("mail.smtp.auth", isAuth ? "true":"false");
    }

    

    private Session getSession(){
        Authenticator authenticator = null;
        if(isAuth){
            authenticator = new SimpleAuthenticator(userName,password);
        }
        Session sendMailSession = Session.getDefaultInstance(props,authenticator);
        
        return sendMailSession;
    }
    
    /**
     * 接收邮件    
     * @throws Exception
     */
    public void receiveEMail() {
            Session session = this.getSession();
            URLName urlname = new URLName(protocol,serverName,Integer.valueOf(serverPort),null,userName,password);
            Store store = null;
            Folder folder = null;
           try{
                store = session.getStore(urlname);
                store.connect(serverName,userName,password);
                folder = store.getFolder("INBOX");
                folder.open(Folder.READ_ONLY);
                
                if (folder instanceof POP3Folder) {
                    
                    POP3Folder pfolder = (POP3Folder) folder;
                    Message[] messages = pfolder.getMessages();
                    for (int i = 0; i < messages.length; i++) {
                        Message msg =  messages[i];
                        String uid = pfolder.getUID(msg);
                        if (!isFindMessage(userName, uid)) {
                            disposeEMail(msg, uid);
                        }
                    }
    
                } else if (folder instanceof IMAPFolder) {
    
                    IMAPFolder inbox = (IMAPFolder) folder;
                    Message[] messages = inbox.getMessages();
                    for (int i = 0; i < messages.length; i++) {
                        Message mimeMessage =  messages[i];
                        String uid = Long.toString(inbox.getUID(mimeMessage));
                        if (!isFindMessage(userName, uid)) {
                            disposeEMail(mimeMessage, uid);
                        }
                    }
    
                } else {
                    System.out.println("No have this folder! ");
                }
          }catch(Exception e){
                System.out.println("receiver email is failed!");
          }finally{
              try {
                if(folder != null)folder.close(false);
                if(store != null)store.close();
              } catch (MessagingException e) {
                System.out.println("folder or store close excetpion!");
              }
               
           }
       
        }
        
        /**
         * 检测此邮件是否已经接收
         * @param user
         * @param uid
         * @return
         */
        public boolean isFindMessage(String user,String uid){
            
            
            return false;
        }
        
        public void disposeEMail(Message msg,String uid) throws Exception{
            //获取主题
            String subject = MimeUtility.decodeText(msg.getSubject());
            System.out.println("subject="+subject);
            //获取发送者地址
            String sender = getFrom(msg);
            System.out.println("sender="+sender);
            //判断是否已读
            boolean isRead = isRead(msg);
            //是否包含附件
            boolean isContainAttch = isContainAttch(msg);
            //判断是否需要回执
            boolean isReplySign =  isReplySign(msg);
            //获取收件人
            String receiverToAddr = this.getMailAddress(msg, "TO");
            System.out.println("receiver To :"+receiverToAddr);
            //获取抄送人
            String receiverCcAddr = this.getMailAddress(msg, "CC");
            System.out.println("receiver CC :"+receiverCcAddr);
            //获取暗送人
            String receiverBccAddr = this.getMailAddress(msg, "BCC");
            System.out.println("receiver BCC :"+receiverBccAddr);
            //获取邮件正文
            
            StringBuffer sb = new StringBuffer();
            getMailContent(msg,sb);
            System.out.println("Date:"+this.getSendDate(msg)+"邮件正文为:"+sb.toString());
            
            System.out.println("是否包含附件"+isContainAttch+"===============是否已读:"+isRead);
            if(isContainAttch){
                this.saveAttchMent(msg);
            }
        }
        /**
         * 获取发送邮件者信息
         * @return
         * @throws MessagingException
         */
        public String getFrom(Message msg) throws MessagingException{
            InternetAddress[] address = (InternetAddress[]) msg.getFrom();
            String from = address[0].getAddress();
            if(from == null){
                from = "";
            }
            String personal = address[0].getPersonal();
            if(personal == null){
                personal = "";
            }
            String fromaddr = personal +"<"+from+">";
            return fromaddr;
        }
        /**
         * 判断此邮件是否已读,如果未读则返回false,已读返回true
         * @return
         * @throws MessagingException
         */
        public boolean isRead(Message msg) throws MessagingException{
            boolean isRead = false;
            Flags flags = msg.getFlags();
            Flags.Flag[] flag = flags.getSystemFlags();
            for(int i=0;i<flag.length;i++){
                if(flag[i]==Flags.Flag.SEEN){
                    isRead = true;
                    break;
                }
            }
            
            return isRead;
        }
        
        /**
         * 判断是是否包含附件
         * @param part
         * @return
         * @throws MessagingException
         * @throws IOException
         */
        public boolean isContainAttch(Part msg) throws MessagingException, IOException{
            boolean flag = false;
            
            String contentType = msg.getContentType();
            if(msg.isMimeType("multipart/*")){
                Multipart multipart = (Multipart) msg.getContent();
                int count = multipart.getCount();
                for(int i=0;i<count;i++){
                    BodyPart bodypart = multipart.getBodyPart(i);
                    String dispostion = bodypart.getDisposition();
                    if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(msg.INLINE))){
                        flag = true;
                    }else if(bodypart.isMimeType("multipart/*")){
                        flag = isContainAttch(bodypart);
                    }else{
                        String conType = bodypart.getContentType();
                        if(conType.toLowerCase().indexOf("appliaction")!=-1){
                            flag = true;
                        }
                        if(conType.toLowerCase().indexOf("name")!=-1){
                            flag = true;
                        }
                    }
                }
            }else if(msg.isMimeType("message/rfc822")){
                flag = isContainAttch((Part)msg.getContent());
            }
            
            return flag;
        }
        
        /**
         * 判断邮件是否需要回执,如需回执返回true,否则返回false
         * @return
         * @throws MessagingException
         */
        public boolean isReplySign(Message msg) throws MessagingException{
            boolean replySign = false;
            String needreply[] = msg.getHeader("Disposition-Notification-TO");
            if(needreply != null){
                replySign = true;
            }
            return replySign;
        }
        
        
        /**
         * 解析邮件,将得到的邮件内容保存到一个stringBuffer对象中,解析邮件 主要根据MimeType的不同执行不同的操作,一步一步的解析
         * @param part
         * @throws MessagingException
         * @throws IOException
         */
        public void getMailContent(Part msg,StringBuffer bodytext) throws MessagingException, IOException{
            String contentType = msg.getContentType();
            int nameindex = contentType.indexOf("name");
            boolean conname = false;
            if(nameindex != -1){
                conname = true;
            }
            System.out.println("CONTENTTYPE:"+contentType);
            if(msg.isMimeType("text/plain")&&!conname){
                bodytext.append((String)msg.getContent());
            }else if(msg.isMimeType("text/html")&&!conname){
                bodytext.append((String)msg.getContent());
            }else if(msg.isMimeType("multipart/*")){
                Multipart multipart = (Multipart) msg.getContent();
                int count = multipart.getCount();
                for(int i=0;i<count;i++){
                    getMailContent(multipart.getBodyPart(i),bodytext);
                }
            }else if(msg.isMimeType("message/rfc822")){
                getMailContent((Part) msg.getContent(),bodytext);
            }
            
        }
        
        /**
         * 保存附件
         * @param part
         * @throws MessagingException
         * @throws IOException
         */
        public void saveAttchMent(Part part) throws MessagingException, IOException{
            String filename = "";
            if(part.isMimeType("multipart/*")){
                Multipart mp = (Multipart) part.getContent();
                for(int i=0;i<mp.getCount();i++){
                    BodyPart mpart = mp.getBodyPart(i);
                    String dispostion = mpart.getDisposition();
                    if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(Part.INLINE))){
                        filename = mpart.getFileName();
                        if(filename.toLowerCase().indexOf("gb2312")!=-1){
                            filename = MimeUtility.decodeText(filename);
                        }
                        saveFile(filename,mpart.getInputStream());
                    }else if(mpart.isMimeType("multipart/*")){
                        saveAttchMent(mpart);
                    }else if(mpart.isMimeType("text/plain") || mpart.isMimeType("text/html")){
                        continue;
                    }else{
                        filename = mpart.getFileName();
                        if(filename != null&&(filename.toLowerCase().indexOf("gb2312")!=-1)){
                            filename = MimeUtility.decodeText(filename);
                        }
                        saveFile(filename,mpart.getInputStream());
                    }
                }
                
            }else if(part.isMimeType("message/rfc822")){
                saveAttchMent((Part) part.getContent());
            }
        }
        
        /**
         * 保存文件内容
         * @param filename
         * @param inputStream
         * @throws IOException
         */
        private void saveFile(String filename, InputStream inputStream)  {
            String osname = System.getProperty("os.name");
            String storedir = saveAttchPath;
            String sepatror = "";
            if(osname == null){
                osname = "";
            }
            
            if(osname.toLowerCase().indexOf("win")!=-1){
                sepatror = "//";
                if(storedir==null||"".equals(storedir)){
                    storedir = "d://temp";
                }
            }else{
                sepatror = "/";
                storedir = "/temp";
            }
            
            File storefile = new File(storedir+sepatror+filename);
            System.out.println("storefile's path:"+storefile.toString());
            
            BufferedOutputStream bos = null;
            BufferedInputStream bis = null;
            
            try {
                bos = new BufferedOutputStream(new FileOutputStream(storefile));
                bis = new BufferedInputStream(inputStream);
                int c;
                while((c= bis.read())!=-1){
                    bos.write(c);
                    bos.flush();
                }
            }  catch (IOException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                System.out.println("*********save file is error *****");
            }finally{
                try {
                    if(bos!=null)bos.close();
                    if(bis!=null)bis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    System.out.println("*********save file is error *****");
                }
                
            }
            
        }
        
        /**
         * 获取邮件发送日期
         * @return
         * @throws MessagingException
         */
        public String getSendDate(Message msg) throws MessagingException{
            Date sendDate = msg.getSentDate();
            SimpleDateFormat smd = new SimpleDateFormat(dateformate);
            return smd.format(sendDate);
        }
        
        /**
         * 获取邮件收件人,抄送,密送的地址和信息。根据所传递的参数不同 "to"-->收件人,"cc"-->抄送人地址,"bcc"-->密送地址
         * @param type
         * @return
         * @throws MessagingException
         * @throws UnsupportedEncodingException
         */
        public String getMailAddress(Message msg,String type) throws MessagingException, UnsupportedEncodingException{
            String mailaddr = "";
            String addrType = type.toUpperCase();
            InternetAddress[] address = null;
            
            if(addrType.equals("TO")||addrType.equals("CC")||addrType.equals("BCC")){
                if(addrType.equals("TO")){
                    address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.TO);
                }
                if(addrType.equals("CC")){
                    address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.CC);
                }
                if(addrType.equals("BCC")){
                    address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.BCC);
                }
                
                if(address != null){
                    for(int i=0;i<address.length;i++){
                        String mail = address[i].getAddress();
                        if(mail == null){
                            mail = "";
                        }else{
                            mail = MimeUtility.decodeText(mail);
                        }
                        String personal = address[i].getPersonal();
                        if(personal == null){
                            personal = "";
                        }else{
                            personal = MimeUtility.decodeText(personal);
                        }
                        String compositeto = personal +"<"+mail+">";
                        mailaddr += ","+compositeto;
                    }
                    mailaddr = mailaddr.substring(1);
                }
            }else{
                throw new RuntimeException("Error email Type!");
            }
            return mailaddr;
        }
        
      //======================================================================
        class SimpleAuthenticator extends Authenticator {
            private String user;
            private String pwd;

            public SimpleAuthenticator(String user, String pwd) {
                this.user = user;
                this.pwd = pwd;
            }

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pwd);
            }
        }
        
        
        public static void main(String[] args) throws MessagingException, IOException {
           
            ReceiveEMailMessage d = new ReceiveEMailMessage();
            try {
                d.init();
                d.receiveEMail();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        
      
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值