精华内容
下载资源
问答
  • imap4命令的详细说明可参考:...imap4有个list命令可以查看邮箱中的所有文件夹,如收件,发件,草稿等,python代码如下: imapclient = imaplib.IMAP4_SSL(imap_server,"993") imapclient.login(email_u...

    imap4命令的详细说明可参考:http://james.apache.org/server/rfclist/imap4/rfc2060.txt
    imap4有个list命令可以查看邮箱中的所有文件夹,如收件箱,发件箱,草稿箱等,python代码如下:

    imapclient = imaplib.IMAP4_SSL(imap_server,"993")
    imapclient.login(email_user,password)
    print(imapclient.list())
    

    对于163邮箱,输出如下: “INBOX"表示收件箱,”&g0l6P3ux-“表示收件箱,”&XfJT0ZAB-"表示发件箱

    ('OK', [b'() "/" "INBOX"', b'(\\Drafts) "/" "&g0l6P3ux-"', b'(\\Sent) "/" "&XfJT0ZAB-"', b'(\\Trash) "/" "&XfJSIJZk-"', b'(\\Junk) "/" "&V4NXPpCuTvY-"', b'() "/" "&dcVr0mWHTvZZOQ-"'])
    

    对于yahoo邮箱,输出如下:

    ('OK', [b'(\\Archive \\HasNoChildren) "/" "Archive"', b'(\\Junk \\HasNoChildren) "/" "Bulk Mail"', b'(\\Drafts \\HasNoChildren) "/" "Draft"', b'(\\HasNoChildren) "/" "Inbox"', b'(\\Sent \\HasNoChildren) "/" "Sent"', b'(\\Trash \\HasNoChildren) "/" "Trash"'])
    

    然后选择发件箱

    response,data=imapclient.select('Sent',False)#针对yahoo邮箱
    response,data=imapclient.select('&XfJT0ZAB-',False)#针对163邮箱
    typ, data = imapclient.search(None, 'ALL')
    mail_number = data[0].split()
    for num in mail_number:
    	typ, data = imapclient.fetch(num, '(UID BODY.PEEK[])')
    	if 'OK'!=typ:
    		print('fetch mail failed!',num)
    		continue
    	#开始处理邮件,可以写到文件中
    	filename = './file/imap/'+mail_box+'/'+email_user+'_imap_'+num.decode()+".eml"
    	emlfile = open(filename,'wb')
    	emlfile.write(data[0][1])
    	emlfile.close()
    

    同理,可以用上述方法下载草稿箱、垃圾箱的邮件

    展开全文
  • 前一阵子,园区的APP要开发手机端的邮箱功能,NND,就这个功能开发了三个版本,我也是醉了,前两个版本都是基于后台去开发给移动端提供接口的,but,后台不愿意了,说是他们工作量太大做不了,...1、收件与发件...

        前一阵子,园区的APP要开发手机端的邮箱功能,NND,就这个功能开发了三个版本,我也是醉了,前两个版本都是基于后台去开发给移动端提供接口的,but,后台不愿意了,说是他们工作量太大做不了,WTF ?!,后来直接说让我们移动端自己开发....,哎,自己开发就开发吧,之前没接触过,也是踩着无数坑过来的呀,希望对大家有所帮助吧,不尽完美,勉强能用,求大神指引方向。看图:

    1、收件箱与发件箱

     废话不多说,直接上代码

    
    /**
     * Created by wz on 2018/10/16.
     * 发件箱
     * 实现上下拉刷新
     */
    
    public class IMAPEmailSentListModel extends BaseModel  {
    
        private int mPageSize = 10;//当有分页加载数据时,每页显示的数据条数
        public ArrayList<EMAIL_LIST> records = new ArrayList<EMAIL_LIST>();
        public int total;
    
        public IMAPEmailSentListModel(Context context) {
            super(context);
        }
    
        /**
         * 列表
         */
        public void list(final String userName, final String password, final String host, final int port, Handler handler) {
            EmailThreadUtil.stop();
            EmailListUP up = new EmailListUP(userName, password, "Sent", host, port, 1, 10,handler,false);//线程
            EmailThreadUtil.execute(up);//线程池
    
        }
    
        /**
         * 更多
         */
        public void more(String userName, String password, String host, int port,Handler handler) {
            EmailThreadUtil.stop();
            int start = (total - records.size() - mPageSize + 1) < 1 ? 1 : (total - records.size() - mPageSize + 1);
            EmailListUP up = new EmailListUP(userName, password, "Sent", host, port, start, total - records.size(),handler,true);
            EmailThreadUtil.execute(up);
    
        }
    }
    

      

    
    /**
     * Created by wz on 2018/10/16.
     * 发件箱列表
     * 实现上下拉刷新
     */
    
    public class IMAPEmailGetListModel extends BaseModel  {
    
        private int mPageSize = 10;//当有分页加载数据时,每页显示的数据条数
        public ArrayList<EMAIL_LIST> records = new ArrayList<EMAIL_LIST>();
        public int total  = 0 ;
    
        public IMAPEmailGetListModel(Context context) {
            super(context);
        }
    
        /**
         * 列表
         */
        public void list(final String userName, final String password, final String host, final int port, Handler handler) {
            EmailThreadUtil.stop();
            EmailListUP up = new EmailListUP(userName, password, "INBOX", host, port, 1, 10,handler,false);
            EmailThreadUtil.execute(up);
    
        }
    
        /**
         * 更多
         */
        public void more(String userName, String password, String host, int port,Handler handler) {
            EmailThreadUtil.stop();
            int start = (total - records.size() - mPageSize + 1) < 1 ? 1 :(total - records.size() - mPageSize + 1);
            EmailListUP up = new EmailListUP(userName, password, "INBOX", host, port, start, total - records.size(),handler,true);
            EmailThreadUtil.execute(up);
    
        }
    
    
    }
    

    上边是我写的发件箱列表和收件箱列表的model, 分别实现两个列表的上拉和加载更多的接口部署。

    
    
    /*
    * 邮件列表entity
    */
    public class EMAIL_LIST implements Serializable {
        public String emailUrl;
    
        public Long email_id;
    
        public String sender; // 发件人
    
        public String subject; // 主题
    
        public String date; // 日期
    
        public String href;
    
        public int allEmmailLenth;
    
        public int hasAttachment; // 是否有附件,0没有,1有
    
        public boolean isRead; // 是否已读
    
        public void fromJson(JSONObject jsonObject) throws JSONException {
            if( null == jsonObject ) {
                return ;
            }
    
            JSONArray subItemArray = new JSONArray();
    
            this.emailUrl = jsonObject.optString("emailUrl");
            this.sender = jsonObject.optString("sender");
            this.subject = jsonObject.optString("subject");
            this.date = jsonObject.optString("date");
            this.href = jsonObject.optString("href");
            this.hasAttachment = jsonObject.optInt("hasAttachment");
            this.isRead = jsonObject.optBoolean("isRead");
            return;
        }
    
        public JSONObject toJson() throws JSONException {
            JSONObject localItemObject = new JSONObject();
            JSONArray itemJSONArray = new JSONArray();
            localItemObject.put("emailUrl", emailUrl);
            localItemObject.put("sender", sender);
            localItemObject.put("subject", subject);
            localItemObject.put("date", date);
            localItemObject.put("href", href);
            localItemObject.put("hasAttachment", hasAttachment);
            localItemObject.put("isRead", isRead);
            return localItemObject;
        }
    }
    
    
    
    /**
     * Created by wz on 2018/10/16.
     * 线程池
     */
    public class EmailThreadUtil {
    
        /**
         * 请求线程池队列,同时允许1个线程操作
         */
        private static ThreadPoolExecutor mPool;
    
        public static Map<String, EmailListUP> downTask = new HashMap<String, EmailListUP>();
    
        //当线程池中的线程小于mCorePoolSize,直接创建新的线程加入线程池执行任务
        private static final int mCorePoolSize = 1;
        //最大线程数
        private static final int mMaximumPoolSize = 3;
        //线程执行完任务后,且队列中没有可以执行的任务,存活的时间,后面的参数是时间单位
        private static final long mKeepAliveTime = 5L;
    
        /**
         * 执行任务,当线程池处于关闭,将会重新创建新的线程池
         */
        private static ExecutorService executor;
    
        //参数说明
        //当线程池中的线程小于mCorePoolSize,直接创建新的线程加入线程池执行任务
        //当线程池中的线程数目等于mCorePoolSize,将会把任务放入任务队列BlockingQueue中
        //当BlockingQueue中的任务放满了,将会创建新的线程去执行,
        //但是当总线程数大于mMaximumPoolSize时,将会抛出异常,交给RejectedExecutionHandler处理
        //mKeepAliveTime是线程执行完任务后,且队列中没有可以执行的任务,存活的时间,后面的参数是时间单位
        //ThreadFactory是每次创建新的线程工厂
        public synchronized static void execute(Runnable run) {
            if (run == null) {
                return;
            }
            if (mPool == null || mPool.isShutdown()) {
                mPool = new ThreadPoolExecutor(mCorePoolSize, mMaximumPoolSize, mKeepAliveTime,
                        TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),
                        Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
            }
            mPool.execute(run);
            //     System.out.println("hashcode"+mPool.hashCode());
           /* if (executor == null || executor.isShutdown()) {
                executor = Executors.newFixedThreadPool(1);
            }
            executor.execute(run);*/
            downTask.put(String.valueOf(System.currentTimeMillis()),(EmailListUP) run);
        }
    
        /**
         * 取消线程池中某个还未执行的任务
         */
        public synchronized static boolean cancel(Runnable run) {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                return mPool.getQueue().remove(run);
            } else {
                return false;
            }
        }
    
        /**
         * 查看线程池中是否还有某个还未执行的任务
         */
        public synchronized static boolean contains(Runnable run) {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                return mPool.getQueue().contains(run);
            } else {
                return false;
            }
        }
    
        /**
         * 立刻关闭线程池,并且正在执行的任务也将会被中断
         */
        public static void stop() {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                mPool.shutdownNow();
            }
        }
    
        /**
         * 平缓关闭单任务线程池,但是会确保所有已经加入的任务都将会被执行完毕才关闭
         */
        public synchronized static void shutdown() {
            if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {
                mPool.shutdownNow();
            }
        }
    
    
    
    }
    

     

    
    /*
    * Create By wz
    * 收件箱、发件箱请求
    */
    
    public class EmailListUP implements Runnable {
    
        private String userName;
        private String password;
        private String type;
        private String host;
        private int start;
        private int end;
        private int port;
        private ArrayList<EMAIL_LIST> list;
        private boolean isFirst = true;
        private Handler handler;
        private boolean isLoadMore;
    
        /**
         * @param userName 姓名
         * @param password 密碼
         * @param type     INBOX收件箱 Sent發件箱
         * @param start    開始位置
         * @param end      結束位置
         * @param isLoadMore     判断是下来刷新还是加载更多
         */
        public EmailListUP(String userName, String password, String type, String host, int port, int start, int end, Handler handler,boolean isLoadMore) {
            this.userName = userName;
            this.password = password;
            this.type = type;
            this.start = start;
            this.host = host;
            this.port = port;
            this.end = end;
            this.handler = handler;
            this.isLoadMore = isLoadMore;
        }
    
        public EmailListUP() {
    
        }
    
        @Override
        public void run() {
    
            getImapEmail();
        }
    
        /**
         * 以imap方式读取邮件,可以判定读取邮件是否为已读
         */
        private void getImapEmail() {
            String user = this.userName;// 邮箱的用户名
            String password = this.password; // 邮箱的密码
    
            Properties prop = System.getProperties();
            prop.put("mail.store.protocol", "imap");
            prop.put("mail.imap.host", this.host);
            prop.put("mail.imap.port", this.port);
    
            Session session = Session.getDefaultInstance(prop);
    
            int total = 0;
            IMAPStore store;
            try {
                store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制,连接服务器
                store.connect(user, password);
                IMAPFolder folder = (IMAPFolder) store.getFolder(this.type);
                folder.open(Folder.READ_WRITE);
                // 获取总邮件数
                total = folder.getMessages().length;
    //            System.out.println("---共有邮件:" + total + " 封---");
                // 得到收件箱文件夹信息,获取邮件列表
                list = new ArrayList<EMAIL_LIST>();
    //            System.out.println("未读邮件数:" + folder.getUnreadMessageCount());
                Message[] messages = null;
              
               //这里提供了folder.getMessages(),folder.getMessages(start,end) 两种方法
               //刚好可以实现分页功能
               if(!isLoadMore) {//下拉刷新
                   if (total < 10) {
                       messages = folder.getMessages();
                   } else {
                       messages = folder.getMessages(total - 10 < 1 ? 1 : (total - 10), total);
                   }
               } else {//加载更多
                   messages = folder.getMessages(start,end);
               }
    
                if (messages.length > 0) {
                    Map<String, Object> map;
                    System.out.println("Messages's length: " + messages.length);
                    ReciveOneMail pmm = null;
                    for (int i = 0; i < messages.length; i++) {
    //                    System.out.println("======================");
                        pmm = new ReciveOneMail((MimeMessage) messages[i]);
    //                    System.out.println("Message " + i + " subject: " + pmm.getSubject());
                        try {
    //                        System.out.println("Message " + i + " sentdate: " + pmm.getSentDate());
    //                        System.out.println("Message " + i + " replysign: " + pmm.getReplySign());
                            boolean isRead;// 用来判断该邮件是否为已读
                            String read;
                            Flags flags = messages[i].getFlags();
    
    //                        System.out.println("Message " + i + " hasRead: " + isRead);
    //                        System.out.println("Message " + i + "  containAttachment: " + pmm.isContainAttach((Part) messages[i]));
    //                        System.out.println("Message " + i + " form: " + pmm.getFrom());
    //                        System.out.println("Message " + i + " to: " + pmm.getMailAddress("to"));
    //                        System.out.println("Message " + i + " cc: " + pmm.getMailAddress("cc"));
    //                        System.out.println("Message " + i + " bcc: " + pmm.getMailAddress("bcc"));
                            pmm.setDateFormat("yy年MM月dd日 HH:mm");
    //                        System.out.println("Message " + i + " sentdate: " + pmm.getSentDate());
    //                        System.out.println("Message " + i + " Message-ID: " + pmm.getMessageId());
                            // 获得邮件内容===============
    //                        pmm.getMailContent((Part) messages[i]);
    //                        System.out.println("Message " + i
    //                                + " bodycontent: \r\n" + pmm.getBodyText());
    //                        String file_path = File.separator + "mnt"
    //                                + File.separator + "sdcard" + File.separator;
    //                        System.out.println(file_path);
    //                        pmm.setAttachPath(file_path);
    //                        pmm.saveAttachMent((Part) messages[i]);
    
    
                            EMAIL_LIST email = new EMAIL_LIST();
                            email.hasAttachment = pmm.isContainAttach((Part) messages[i]) ? 1 : 0;
                            email.sender = pmm.getFrom();
                            email.subject = pmm.getSubject();
                            email.date = pmm.getSentDate();
                            email.email_id = folder.getUID(messages[i]);//邮箱ID,用来获取单个邮件详情的
                            email.allEmmailLenth = total;
                            if (flags.contains(Flags.Flag.SEEN)) {
                                email.isRead = true;
                            } else {
                                email.isRead = false;
                            }
                            list.add(email);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
    
                     //我这里 用的是handler给view层反馈信息的 ,大佬可以自行修改
                    android.os.Message msgg = new android.os.Message();
                    msgg.what = CustomMessageConstant.IMAP_LIST_REFRESH;
                    if (type.equals("INBOX")) {//收件箱
                        msgg.arg1 = EmailIMAPListView.INBOX;
                    } else if (type.equals("Sent")) {//发件箱
                        msgg.arg1 = EmailIMAPListView.OUTBOX;
                    }
                    if (!isLoadMore) {//下拉刷新
                        msgg.arg2 = 0;
                    } else { //上拉更多
                        msgg.arg2 = 1;
                    }
                    msgg.obj = list;
                    handler.sendMessage(msgg);
                }
            } catch (javax.mail.NoSuchProviderException e) {
                e.printStackTrace();
            } catch (AuthenticationFailedException e) {
             //此异常是个坑,会崩溃,原因:邮箱账户密码验证不通过
                android.os.Message msgg = new android.os.Message();
                msgg.what = CustomMessageConstant.IMAP_NAME_INVLID;
                handler.sendMessage(msgg);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
    
        }
    
    }
    
    //大佬们可以根据自己的上下拉控件,自行修改
    Handler mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                handleMsg(msg);
            }
        };
     private void handleMsg(Message msg){
             if (msg.what == CustomMessageConstant.IMAP_LIST_REFRESH) {
                 if (msg.arg1 == INBOX) {//收件箱
                     mListView.stopRefresh();
                     mListView.stopLoadMore();
                    if (msg.arg2 == 0) {//下拉
                        mGetModel.total = ((ArrayList<EMAIL_LIST>) msg.obj).get(0).allEmmailLenth;
                        mGetModel.records.clear();
                        mGetModel.records = (ArrayList<EMAIL_LIST>) msg.obj;
                    } else if (msg.arg2 == 1) {//上拉
                        mGetModel.records.addAll((ArrayList<EMAIL_LIST>) msg.obj);
                    }
                     if (mEmailAdapter == null) {
                         mEmailAdapter = new EmailIAMPAdapter(getContext(), mGetModel.records,INBOX);
                         mListView.setAdapter(mEmailAdapter);
                     } else {
                         mEmailAdapter.mData = mGetModel.records;
                         mEmailAdapter.sortAndNotifyDataSetChanged();
                     }
                     if (mGetModel.total <= mGetModel.records.size()) {
                         mListView.setPullLoadEnable(false);
                     } else {
                         mListView.setPullLoadEnable(true);
                     }
    
                 } else if (msg.arg1 == OUTBOX) {//发件箱
                     mListView.stopRefresh();
                     mListView.stopLoadMore();
                    if (msg.arg2 == 0) {//下拉
                        mSendModel.total = ((ArrayList<EMAIL_LIST>) msg.obj).get(0).allEmmailLenth;
                        mSendModel.records.clear();
                        mSendModel.records = (ArrayList<EMAIL_LIST>) msg.obj;
                    } else if (msg.arg2 == 1) {//上拉
                        mSendModel.records.addAll((ArrayList<EMAIL_LIST>) msg.obj);
                    }
                     if (mEmailAdapter == null) {
                         mEmailAdapter = new EmailIAMPAdapter(getContext(), mSendModel.records,OUTBOX);
                         mListView.setAdapter(mEmailAdapter);
                     } else {
                         mEmailAdapter.mData = mSendModel.records;
                         mEmailAdapter.sortAndNotifyDataSetChanged();
                     }
                     if (mSendModel.total <= mSendModel.records.size()) {
                         mListView.setPullLoadEnable(false);
                     } else {
                         mListView.setPullLoadEnable(true);
                     }
                 }
             } else if (msg.what == CustomMessageConstant.IMAP_NAME_INVLID){
                 ToastUtil.toastShow(getContext(),"邮箱账号密码错误");
             }
         }

     

    2、邮件详情与附件下载

    上边获取邮件列表的时候,获取到的UID,这里用到去获取邮件详情

    EmailThreadUtil.stop();
    EmailDetailUP  up = new EmailDetailUP(SESSION.getInstance().getEmail(), SESSION.getInstance().getOAPassword(), mEmailType, SESSION.getInstance().getEmailHost(), SESSION.getInstance().getEmailPost(),emailUID, handler);
            EmailThreadUtil.execute(up);
    
    
    /**
    *Create by wz
    * 邮件详情请求
    *
    */
    
    public class EmailDetailUP extends EmailListUP {
    
        private String userName;
        private String password;
        private String type;
        private String host;
        private int port;
        private ArrayList<EMAIL> list;
        private boolean isFirst = true;
        private Handler handler;
        private long uid;
    
        private ReciveOneMail pmm;
    
        /**
         * @param userName 姓名
         * @param password 密碼
         * @param type     INBOX收件箱 Sent發件箱
         */
        public EmailDetailUP(String userName, String password, String type, String host, int port,long uid,Handler handler) {
            this.userName = userName;
            this.password = password;
            this.type = type;
            this.host = host;
            this.port = port;
            this.uid = uid;
            this.handler = handler;
        }
    
    
        @Override
        public void run() {
    
            getImapEmail();
        }
    
        /**
         * 以imap方式读取邮件,可以判定读取邮件是否为已读
         */
        private void getImapEmail() {
            String user = this.userName;// 邮箱的用户名
            String password = this.password; // 邮箱的密码
    
            Properties prop = System.getProperties();
            prop.put("mail.store.protocol", "imap");
            prop.put("mail.imap.host", this.host);
            prop.put("mail.imap.port", this.port);
    
            Session session = Session.getDefaultInstance(prop);
    
            int total = 0;
            IMAPStore store;
            try {
                store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制,连接服务器
    
                store.connect(user, password);
    
                IMAPFolder folder = (IMAPFolder) store.getFolder(this.type);
                folder.open(Folder.READ_WRITE);
                // 获取总邮件数
                total = folder.getMessages().length;
    //            System.out.println("---共有邮件:" + total + " 封---");
                // 得到收件箱文件夹信息,获取邮件列表
                list = new ArrayList<EMAIL>();
    //            System.out.println("未读邮件数:" + folder.getUnreadMessageCount());
                Message[] messages = new Message[1];
                //messages = folder.getMessages(start, end);
         //其实跟获取列表没什么不同,只是用到的方法不同而已
                Message message = folder.getMessageByUID(uid);
                messages[0] = message;
                if (messages.length > 0) {
                    Map<String, Object> map;
    //                System.out.println("Messages's length: " + messages.length);
    
                    for (int i = 0; i < messages.length; i++) {
    //                    System.out.println("======================");
                        pmm = new ReciveOneMail((MimeMessage) messages[i]);
    //                    System.out.println("Message " + i + " subject: " + pmm.getSubject());
                        try {
    //                        System.out.println("Message " + i + " sentdate: " + pmm.getSentDate());
    //                        System.out.println("Message " + i + " replysign: " + pmm.getReplySign());
                            boolean isRead;// 用来判断该邮件是否为已读
                            String read;
                            Flags flags = messages[i].getFlags();
                            if (flags.contains(Flags.Flag.SEEN)) {
    //                            System.out.println("这是一封已读邮件");
                                isRead = true;
                                read = "已读";
                            } else {
    //                            System.out.println("未读邮件");
                                isRead = false;
                                read = "未读";
                            }
                            //设置为已读
                            messages[i].setFlag(Flags.Flag.SEEN, true);
    //                        System.out.println("Message " + i + " hasRead: " + isRead);
                            System.out.println("Message " + i + "  containAttachment: " + pmm.isContainAttach((Part) messages[i]));
    //                        System.out.println("Message " + i + " form: " + pmm.getFrom());
    //                        System.out.println("Message " + i + " to: " + pmm.getMailAddress("to"));
    //                        System.out.println("Message " + i + " cc: " + pmm.getMailAddress("cc"));
    //                        System.out.println("Message " + i + " bcc: " + pmm.getMailAddress("bcc"));
                            pmm.setDateFormat("yy年MM月dd日 HH:mm");
    //                        System.out.println("Message " + i + " sentdate: " + pmm.getSentDate());
    //                        System.out.println("Message " + i + " Message-ID: " + pmm.getMessageId());
                            // 获得邮件内容===============
                            pmm.getMailContent((Part) messages[i]);
    //                        System.out.println("Message " + i
    //                                + " bodycontent: \r\n" + pmm.getBodyText());
    //                        String file_path = File.separator + "mnt"
    //                                + File.separator + "sdcard" + File.separator;
    //                        System.out.println(file_path);
    //                        pmm.setAttachPath(file_path);
                            // 下载附件并保存到本地,此处包含附件以及内嵌资源(内嵌表情,内嵌图片等)
                            pmm.saveAttachMent((Part) messages[i],pmm.getSentDate());
                            EMAIL email = new EMAIL();
                            email.sender_email = pmm.getFrom();
                            if(pmm.getFrom().split("<")[0].equals("")){
                                email.sender_name = pmm.getFrom().split("@")[0].split("<")[1];
                            }else {
                                email.sender_name = pmm.getFrom().split("<")[0];
                            }
                            email.content = pmm.getBodyText();
                            email.subject = pmm.getSubject();
                            email.time = pmm.getSentDate();
                            email.to = pmm.getMailList("to");
                            email.copy = pmm.getMailList("cc");
                            email.attachment = pmm.getAttachMent((Part) messages[i]);
                            list.add(email);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    //此处 大佬可自行更换,憋人用的hanlder
                    android.os.Message msgg = new android.os.Message();
                    msgg.what = CustomMessageConstant.IMAP_DETAIL_REFRESH;
                    if (type.equals("INBOX")) {//收件箱
                        msgg.arg1 = EmailIMAPListView.INBOX;
                    } else if (type.equals("Sent")) {//发件箱
                        msgg.arg1 = EmailIMAPListView.OUTBOX;
                    }
                    msgg.obj = list;
                    handler.sendMessage(msgg);
                }
            } catch (javax.mail.NoSuchProviderException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
    
        }
    
    
    }
    

     

    
    
    /**
     * 接收邮箱中的邮件,可以接收带附件的
     * (目前接收的邮件中含有中文内容,会出现乱码,但是标题不会乱码)
     * 邮件中的内容如果用专门的阅读器也不会出现乱码现象,图片等都可以下载
     */
    @SuppressLint("DefaultLocale")
    public class ReciveOneMail {
    
        private MimeMessage mimeMessage = null;
        private String saveAttachPath = ""; // 附件下载后的存放目录
        private StringBuffer bodytext = new StringBuffer();// 存放邮件内容
        private String dateformat = "yy-MM-dd HH:mm"; // 默认的日前显示格式
    
        public ReciveOneMail(MimeMessage mimeMessage) {
            this.mimeMessage = mimeMessage;
        }
    
        public void setMimeMessage(MimeMessage mimeMessage) {
            this.mimeMessage = mimeMessage;
        }
    
        /**
         * 获得发件人的地址和姓名
         */
        public String getFrom() throws Exception {
            InternetAddress address[] = (InternetAddress[]) mimeMessage.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;
        }
    
        /**
         * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
         */
        @SuppressLint("DefaultLocale")
        public String getMailAddress(String type) throws Exception {
            String mailaddr = "";
            String addtype = type.toUpperCase();
            InternetAddress[] address = null;
            if (addtype.equals("TO") || addtype.equals("CC")
                    || addtype.equals("BCC")) {
                if (addtype.equals("TO")) {
                    address = (InternetAddress[]) mimeMessage
                            .getRecipients(Message.RecipientType.TO);
                } else if (addtype.equals("CC")) {
                    address = (InternetAddress[]) mimeMessage
                            .getRecipients(Message.RecipientType.CC);
                } else {
                    address = (InternetAddress[]) mimeMessage
                            .getRecipients(Message.RecipientType.BCC);
                }
                if (address != null) {
                    for (int i = 0; i < address.length; i++) {
                        String email = address[i].getAddress();
                        if (email == null)
                            email = "";
                        else {
                            email = MimeUtility.decodeText(email);
                        }
                        String personal = address[i].getPersonal();
                        if (personal == null)
                            personal = "";
                        else {
                            personal = MimeUtility.decodeText(personal);
                        }
                        String compositeto = personal + "<" + email + ">";
                        mailaddr += "," + compositeto;
                    }
                    mailaddr = mailaddr.substring(1);
                }
            } else {
                throw new Exception("Error emailaddr type!");
            }
            return mailaddr;
        }
    
        @SuppressLint("DefaultLocale")
        public ArrayList<RECIPIENTS> getMailList(String type) throws Exception {
            ArrayList<RECIPIENTS> toOrccList = new ArrayList<RECIPIENTS>(); // 收件人
            String mailaddr = "";
            String addtype = type.toUpperCase();
            InternetAddress[] address = null;
            if (addtype.equals("TO") || addtype.equals("CC")
                    || addtype.equals("BCC")) {
                if (addtype.equals("TO")) {
                    address = (InternetAddress[]) mimeMessage
                            .getRecipients(Message.RecipientType.TO);
                } else if (addtype.equals("CC")) {
                    address = (InternetAddress[]) mimeMessage
                            .getRecipients(Message.RecipientType.CC);
                } else {
                    address = (InternetAddress[]) mimeMessage
                            .getRecipients(Message.RecipientType.BCC);
                }
                toOrccList.clear();
                if (address != null) {
                    for (int i = 0; i < address.length; i++) {
                        String email = address[i].getAddress();
                        if (email == null)
                            email = "";
                        else {
                            email = MimeUtility.decodeText(email);
                        }
                        String personal = address[i].getPersonal();
                        if (personal == null)
                            personal = "";
                        else {
                            personal = MimeUtility.decodeText(personal);
                        }
                        String compositeto = personal + "<" + email + ">";
                        mailaddr += "," + compositeto;
                        RECIPIENTS recipients = new RECIPIENTS();
                        recipients.address = email;
                        recipients.name = personal;
                        toOrccList.add(recipients);
                    }
                    mailaddr = mailaddr.substring(1);
                }
            } else {
                throw new Exception("Error emailaddr type!");
            }
            return toOrccList;
        }
    
        /**
         * 获得邮件主题
         */
        public String getSubject() throws MessagingException {
            String subject = "";
            try {
                subject = MimeUtility.decodeText(mimeMessage.getSubject());
                if (subject == null)
                    subject = "";
            } catch (Exception exce) {
            }
            return subject;
        }
    
        /**
         * 获得邮件发送日期
         */
        @SuppressLint("SimpleDateFormat")
        public String getSentDate() throws Exception {
            Date sentdate = mimeMessage.getSentDate();
            SimpleDateFormat format = new SimpleDateFormat(dateformat);
            return format.format(sentdate);
        }
    
        /**
         * 获得邮件正文内容
         */
        public String getBodyText() {
            return bodytext.toString();
        }
    
        /**
         * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析
         */
        public void getMailContent(Part part) throws Exception {
            String contenttype = part.getContentType();
            int nameindex = contenttype.indexOf("name");
            boolean conname = false;
            if (nameindex != -1)
                conname = true;
            System.out.println("CONTENTTYPE: " + contenttype);
            if (part.isMimeType("text/plain") && !conname) {
                bodytext.append((String) part.getContent());
            } else if (part.isMimeType("text/html") && !conname) {
                bodytext.append((String) part.getContent());
            } else if (part.isMimeType("multipart/*")) {
                Multipart multipart = (Multipart) part.getContent();
                int counts = multipart.getCount();
                for (int i = 0; i < counts; i++) {
                    getMailContent(multipart.getBodyPart(i));
                }
            } else if (part.isMimeType("message/rfc822")) {
                getMailContent((Part) part.getContent());
            } else {
            }
        }
    
        /**
         * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
         */
        public boolean getReplySign() throws MessagingException {
            boolean replysign = false;
            String needreply[] = mimeMessage
                    .getHeader("Disposition-Notification-To");
            if (needreply != null) {
                replysign = true;
            }
            return replysign;
        }
    
        /**
         * 获得此邮件的Message-ID
         */
        public String getMessageId() throws MessagingException {
            return mimeMessage.getMessageID();
        }
    
        /**
         * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】pop3协议使用时不能判断。
         */
        public boolean isNew() throws MessagingException {
            boolean isnew = false;//由于isnew设为false所以每次显示的都为未读
            Flags flags = ((Message) mimeMessage).getFlags();
    //        System.out.println("--------flags-------" + flags);
            Flags.Flag[] flag = flags.getSystemFlags();
    //        System.out.println("----flag----" + flag);
    //        System.out.println("flags's length: " + flag.length);
            for (int i = 0; i < flag.length; i++) {
    //            System.out.println("flag=======" + flag[i]);
    //            System.out.println("-=-=-=Flags.Flag.SEEN=-=-=-=" + Flags.Flag.SEEN);
                if (flag[i] == Flags.Flag.SEEN) {
                    isnew = true;
    //                System.out.println("seen Message.......");
                    break;
                }
            }
            return isnew;
        }
    
        /**
         * 判断此邮件是否包含附件
         */
        @SuppressLint("DefaultLocale")
        public boolean isContainAttach(Part part) throws Exception {
            boolean attachflag = false;
            if (part.isMimeType("multipart/*")) {
                Multipart mp = (Multipart) part.getContent();
                for (int i = 0; i < mp.getCount(); i++) {
                    BodyPart mpart = mp.getBodyPart(i);
                    String disposition = mpart.getDisposition();
                    if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE)))) {
                        if (mpart.getContentType().toLowerCase().indexOf("name") != -1) {
                            attachflag = true;
                        } else if (mpart.getFileName() != null) {
                            attachflag = true;
                        } else {
                            attachflag = false;
                        }
    
                    } /*else if((disposition != null) && (disposition.equals(Part.INLINE))){
                        attachflag = false;
                    }*/ else if (mpart.isMimeType("multipart/*")) {
                        attachflag = isContainAttach((Part) mpart);
                    } else {
                        String contype = mpart.getContentType();
                        if (contype.toLowerCase().indexOf("application") != -1)
                            attachflag = true;
                        if (contype.toLowerCase().indexOf("name") != -1)
                            attachflag = true;
                    }
                }
            } else if (part.isMimeType("message/rfc822")) {
                attachflag = isContainAttach((Part) part.getContent());
            }
            return attachflag;
        }
    
        /**
         * 【保存附件】
         */
        @SuppressLint("DefaultLocale")
        public void saveAttachMent(Part part, String emailTimei) throws Exception {
            if (isContainAttach(part)) {
                String fileName = "";
                if (part.isMimeType("multipart/*")) {
                    Multipart mp = (Multipart) part.getContent();
                    for (int i = 0; i < mp.getCount(); i++) {
                        BodyPart mpart = mp.getBodyPart(i);//主体部分得到处理
                        if (mpart.isMimeType("multipart/*")) {
                            saveAttachMent(mpart, emailTimei);
                        } else {
                            String disposition = mpart.getDisposition();
                            if ((disposition != null)
                                    && (disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE)))) {//ATTACHMENT附件
                                fileName = mpart.getFileName();
                                if (fileName != null) {
                                   /* if (fileName.toLowerCase().indexOf("gb2312") != -1 || fileName.toLowerCase().indexOf("gb1803") != -1 ||fileName.toLowerCase().indexOf("gbk") != -1) {
                                        fileName = MimeUtility.decodeText(fileName);
                                    }
                                    if (fileName.toLowerCase().indexOf("utf-8") != -1) {//gb18030
                                        fileName = MimeUtility.decodeText(fileName);
                                    }*/
                                    fileName = MimeUtility.decodeText(fileName);
                                    saveFile(emailTimei + fileName, mpart.getInputStream());//邮件发送时间+附件名称 生成新的附件名称,这里为了防止附件重名
                                }
                            } else {
                                fileName = mpart.getFileName();
                                if (fileName == null && mpart.getContentType().contains("name=")) {
                                    fileName = mpart.getContentType().split("name=")[1];
                                }
                                if (fileName != null) {
                                    /*if ((fileName.toLowerCase().indexOf("gb2312") != -1)
                                            && (fileName.toLowerCase().indexOf("utf-8") != -1)
                                            ) {*/
    
                                    fileName = MimeUtility.decodeText(fileName);
                                    saveFile(emailTimei + fileName, mpart.getInputStream());
    //                                }
                                }
                            }
                        }
                    }
                } else if (part.isMimeType("message/rfc822")) {
                    saveAttachMent((Part) part.getContent(), emailTimei);
                }
            }
        }
    
        /**
         * 【获取附件】
         */
        ArrayList<ATTACHMENT> attachments = new ArrayList<ATTACHMENT>();
    
        @SuppressLint("DefaultLocale")
        public ArrayList<ATTACHMENT> getAttachMent(Part part) throws Exception {
    
            ATTACHMENT attachment;
    
            if (part.isMimeType("multipart/*")) {
                Multipart mp = (Multipart) part.getContent();
                for (int i = 0; i < mp.getCount(); i++) {
                    BodyPart mpart = mp.getBodyPart(i);//主体部分得到处理
                    if (mpart.isMimeType("multipart/*")) {
                        getAttachMent(mpart);
                    } else {
                        String disposition = mpart.getDisposition();
                        if ((disposition != null)
                                && ((disposition.equals(Part.ATTACHMENT)) || (disposition
                                .equals(Part.INLINE)))) {//ATTACHMENT附件,INLINE嵌入
                            String fileName = "";
                            fileName = mpart.getFileName();
    
                            if (fileName != null) {
                               /* if (fileName.toLowerCase().indexOf("gb2312") != -1 || fileName.toLowerCase().indexOf("gb1803") != -1 || fileName.toLowerCase().indexOf("gbk") != -1 ) {//gb18030
                                    fileName = MimeUtility.decodeText(fileName);
                                }
                                if (fileName.toLowerCase().indexOf("utf-8") != -1) {//gb18030
                                    fileName = MimeUtility.decodeText(fileName);
                                }*/
                                fileName = MimeUtility.decodeText(fileName);
                                int fileSize = mpart.getSize();
                                attachment = new ATTACHMENT();
                                attachment.filesize = GetFileSize.FormetFileSize(fileSize);
                                //附件没有cid,内嵌图片表情等资源有Cid
                                attachment.cid = getCid(mpart);
                                attachment.realname = fileName.replace("\\","");
                                attachment.filelocalPath = AppStoragePath.getCachePath() + File.separator + fileName;
                                attachments.add(attachment);
                            }
                        } else {
                            String fileName = "";
                            fileName = mpart.getFileName();
                            if (fileName == null && mpart.getContentType().contains("name=")) {
                                fileName = mpart.getContentType().split("name=")[1];
                            }
                            if (fileName != null) {
                                   /* if (fileName.toLowerCase().indexOf("gb2312") != -1 && fileName.toLowerCase().indexOf("gb1803") != -1 && fileName.toLowerCase().indexOf("gbk") != -1
                                    && (fileName.toLowerCase().indexOf("utf-8") != -1)
                                    ) {
                                      fileName = MimeUtility.decodeText(fileName);
                                    }*/
                                fileName = MimeUtility.decodeText(fileName);
                                attachment = new ATTACHMENT();
                                attachment.filesize = GetFileSize.FormetFileSize(mpart.getSize());
               //附件没有cid,内嵌图片表情等资源有Cid
                                attachment.cid = getCid(mpart);
                                attachment.realname = fileName.replace("\\","");
                                attachment.filelocalPath = AppStoragePath.getCachePath() + File.separator + fileName;
                                attachments.add(attachment);
                            }
                        }
                    }
                }
            } else if (part.isMimeType("message/rfc822")) {
                getAttachMent((Part) part.getContent());
            }
            return attachments;
        }
    
        /**
         * 获取内嵌资源id
         * 判断是否是表情或者正文图片的重要依据 ,判断是否有cid
         * @param p
         * @return
         * @throws MessagingException
         */
        public static String getCid(Part p) throws MessagingException {
            String content, cid;
            String[] headers = p.getHeader("Content-Id");
            if (headers != null && headers.length > 0) {
                content = headers[0];
            } else {
                return null;
            }
            if (content.startsWith("<") && content.endsWith(">")) {
                cid = "cid:" + content.substring(1, content.length() - 1);
            } else {
                cid = "cid:" + content;
            }
            return cid;
        }
    
    
        /**
         * 【设置附件存放路径】
         */
        public void setAttachPath(String attachpath) {
            this.saveAttachPath = attachpath;
        }
    
        /**
         * 【设置日期显示格式】
         */
        public void setDateFormat(String format) throws Exception {
            this.dateformat = format;
        }
    
        /**
         * 【获得附件存放路径】
         */
        public String getAttachPath() {
            return saveAttachPath;
        }
    
        /**
         * 【真正的保存附件到指定目录里】
         */
        @SuppressLint("DefaultLocale")
        public void saveFile(String fileName, InputStream in) throws Exception {
    
            fileName = fileName.replace("\\","");
            File storefile = new File(AppStoragePath.getCachePath() + File.separator + fileName);
            if (!storefile.exists()) {
                storefile.createNewFile();
    
                BufferedOutputStream bos = null;
                BufferedInputStream bis = null;
                try {
                    bos = new BufferedOutputStream(new FileOutputStream(storefile));
                    bis = new BufferedInputStream(in);
                    int c;
                    while ((c = bis.read()) != -1) {
                        bos.write(c);
                        bos.flush();
                    }
                } catch (Exception exception) {
                } finally {
                    bos.close();
                    bis.close();
                }
            }
        }
    
    
    // 附件下载完成 回调接口
        public interface OnDownloadListener {
            void onSuccess();
    
            void onFaild();
        }
    
        OnDownloadListener onDownloadListener;
    }
    

     

    
    
    /**
    * Create by wz
    * 附件entity
    */
    
    public class ATTACHMENT implements Serializable {
        public String fileid; // id
    
        public String realname; // 名称
    
        public String filesize; // 大小
    
        public String filelocalPath ;//文件本地路徑
    
        public String cid;
    
    
        public void fromJson(JSONObject jsonObject) throws JSONException {
            if( null == jsonObject ) {
                return ;
            }
    
            JSONArray subItemArray = new JSONArray();
    
            this.fileid = jsonObject.optString("fileid");
            this.realname = jsonObject.optString("realname");
            this.filesize = jsonObject.optString("filesize");
            this.cid = jsonObject.optString("cid");
            return;
        }
    
        public JSONObject toJson() throws JSONException {
            JSONObject localItemObject = new JSONObject();
            JSONArray itemJSONArray = new JSONArray();
            localItemObject.put("fileid", fileid);
            localItemObject.put("realname", realname);
            localItemObject.put("filesize", filesize);
            localItemObject.put("cid", cid);
            return localItemObject;
        }
    }
    
    
    
    /**
    * Create by wz
    * 邮件详情entity
    * 此处与收发邮箱列表entity区别:列表出不需要有附件的详细内容,此处确实需要
    */
    
    public class EMAIL implements Serializable {
        public String unid; // 邮件unid
    
        public String sender_email; // 发件人
    
        public String sender_name; // 发件人
    
        public ArrayList<RECIPIENTS> to = new ArrayList<RECIPIENTS>(); // 收件人
    
        public ArrayList<RECIPIENTS> copy = new ArrayList<RECIPIENTS>(); // 抄送
    
        public String time; // 时间
    
        public String message_id; // id
    
        public String subject; // 主题
    
        public String content; // 内容
    
        public ArrayList<ATTACHMENT> attachment = new ArrayList<ATTACHMENT>(); // 附件
    
        public void fromJson(JSONObject jsonObject) throws JSONException {
            if( null == jsonObject ) {
                return ;
            }
    
            JSONArray subItemArray = new JSONArray();
            this.unid = jsonObject.optString("unid");
            this.sender_email = jsonObject.optString("sender_email");
            this.sender_name = jsonObject.optString("sender_name");
            subItemArray = jsonObject.optJSONArray("to");
            if(null != subItemArray) {
                for(int i = 0;i < subItemArray.length();i++) {
                    JSONObject subItemObject = subItemArray.getJSONObject(i);
                    RECIPIENTS subItem = new RECIPIENTS();
                    subItem.fromJson(subItemObject);
                    this.to.add(subItem);
                }
            }
            subItemArray = jsonObject.optJSONArray("copy");
            if(null != subItemArray) {
                for(int i = 0;i < subItemArray.length();i++) {
                    JSONObject subItemObject = subItemArray.getJSONObject(i);
                    RECIPIENTS subItem = new RECIPIENTS();
                    subItem.fromJson(subItemObject);
                    this.copy.add(subItem);
                }
            }
            this.time = jsonObject.optString("time");
            this.message_id = jsonObject.optString("message_id");
            this.subject = jsonObject.optString("subject");
            this.content = jsonObject.optString("content");
            subItemArray = jsonObject.optJSONArray("attachment");
            if(null != subItemArray) {
                for(int i = 0;i < subItemArray.length();i++) {
                    JSONObject subItemObject = subItemArray.getJSONObject(i);
                    ATTACHMENT subItem = new ATTACHMENT();
                    subItem.fromJson(subItemObject);
                    this.attachment.add(subItem);
                }
            }
            return;
        }
    
        public JSONObject toJson() throws JSONException {
            JSONObject localItemObject = new JSONObject();
            JSONArray itemJSONArray = new JSONArray();
            localItemObject.put("unid", unid);
            localItemObject.put("sender_email", sender_email);
            localItemObject.put("sender_name", sender_name);
            itemJSONArray = new JSONArray();
            for(int i =0; i< to.size(); i++) {
                RECIPIENTS itemData =to.get(i);
                JSONObject itemJSONObject = itemData.toJson();
                itemJSONArray.put(itemJSONObject);
            }
            localItemObject.put("to", itemJSONArray);
    
            itemJSONArray = new JSONArray();
            for(int i =0; i< copy.size(); i++) {
                RECIPIENTS itemData =copy.get(i);
                JSONObject itemJSONObject = itemData.toJson();
                itemJSONArray.put(itemJSONObject);
            }
            localItemObject.put("copy", itemJSONArray);
    
            localItemObject.put("time", time);
            localItemObject.put("message_id", message_id);
            localItemObject.put("subject", subject);
            localItemObject.put("content", content);
            itemJSONArray = new JSONArray();
            for(int i =0; i< attachment.size(); i++) {
                ATTACHMENT itemData =attachment.get(i);
                JSONObject itemJSONObject = itemData.toJson();
                itemJSONArray.put(itemJSONObject);
            }
            localItemObject.put("attachment", itemJSONArray);
    
            return localItemObject;
        }
    }
    

     

     

    //邮件详情页面拿到数据后进行展示 ,bindData();
    Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == CustomMessageConstant.IMAP_DETAIL_REFRESH) {
                    if(((ArrayList<EMAIL>) msg.obj).size() > 0) {
                        mEmail = ((ArrayList<EMAIL>) msg.obj).get(0);
                        bindData();
                    }
                } else if (msg.what == CustomMessageConstant.IMAP_DETAIL_DOWNLOAD) {
                    if (mProgressDialog != null && mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
                }
            }
        };

    3、邮件发送与转发回复,已经添加到发件箱(此处一坑,如果不手动添加进去,发件箱是不会刷新出你发送成功的邮件的)

     

     //发送邮件
                EmailThreadUtil.stop();
                SentEmailUP sentEmailUP = new SentEmailUP(theme,content,mSelectUsersShou,mSelectUsersChao,mSelectUsersMi,mFiles,handler,mEmail);
                EmailThreadUtil.execute(sentEmailUP);

     

    
    
    /*
    * Create by wz
    * 发送邮件请求 以及 保存件到发件箱
    */
    
    public class SentEmailUP extends EmailListUP {
    
        private String userName;
        private String password;
        private String host;
        private int port;
        private ArrayList<RECIPIENTS> to;
        private ArrayList<RECIPIENTS> cc;
        private ArrayList<RECIPIENTS> bcc;
        private EMAIL mEmail;
        private String content;
        private String subject;
        private ArrayList<String> mFiles;
        private Handler handler;
    
    
        /**
         * @param subject 主题
         * @param content 内容
         * @param to      收件者
         * @param cc      抄送
         * @param bcc     密送
         * @param mFiles  附件
         * @param handler
         */
        public SentEmailUP(String subject, String content, ArrayList<RECIPIENTS> to, ArrayList<RECIPIENTS> cc, ArrayList<RECIPIENTS> bcc, ArrayList<String> mFiles, Handler handler,EMAIL mEmail) {
            this.to = to;
            this.content = content;
            this.subject = subject;
            this.mFiles = mFiles;
            this.cc = cc;
            this.bcc = bcc;
            this.handler = handler;
            this.userName = SESSION.getInstance().getEmail();
            this.password = SESSION.getInstance().getOAPassword();
            this.host = SESSION.getInstance().getEmailHost();
            this.port = SESSION.getInstance().getSendEmailPost();
            this.mEmail = mEmail;
    
        }
    
        @Override
        public void run() {
            sendAttachmentMail();
        }
    
        /**
         * 发送附件邮件
         *
         * @throws Exception
         */
        public void sendAttachmentMail() {
            Properties pro = System.getProperties();
            pro.setProperty("mail.transport.protocol", "smtp"); // 设置邮件传输采用的协议smtp
            pro.put("mail.smtp.host", this.host);
            pro.put("mail.smtp.port", this.port);
            pro.put("mail.smtp.auth", "true");
            pro.setProperty("mail.smtp.starttls.enable", "true");     // 设置验证机制
    
            try {
                // 根据邮件会话属性和密码验证器构造一个发送邮件的session
                Session sendMailSession = Session.getInstance(pro,
                        new Authenticator() {
                            @Override
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(userName, password);
                            }
                        });
                // 根据session创建一个邮件消息
                Message mailMessage = new MimeMessage(sendMailSession);
                // 设置邮件消息的发送者
                mailMessage.setFrom(new InternetAddress(userName, SESSION.getInstance().getRealname(), "UTF-8"));
    
                // 创建邮件的接收者地址,并设置到邮件消息中
                if (to.size() > 0) {
                    InternetAddress[] sendTo = new InternetAddress[to.size()];
                    for (int i = 0; i < to.size(); i++) {
                        String address;
                        if (to.get(i).address.contains("<") && to.get(i).address.contains(">")) {
                            address = to.get(i).address.split("<")[1].split(">")[0];
                        } else {
                            address = to.get(i).address;
                        }
                        sendTo[i] = new InternetAddress(address, to.get(i).name, "UTF-8");
                    }
                    mailMessage.addRecipients(Message.RecipientType.TO, sendTo);
                }
    
                // 创建邮件的抄送者地址,并设置到邮件消息中
                if (cc.size() > 0) {
                    InternetAddress[] ccTo = new InternetAddress[cc.size()];
                    for (int i = 0; i < cc.size(); i++) {
                        String address;
                        if (cc.get(i).address.contains("<") && cc.get(i).address.contains(">")) {
                            address = cc.get(i).address.split("<")[1].split(">")[0];
                        } else {
                            address = cc.get(i).address;
                        }
                        ccTo[i] = new InternetAddress(address, to.get(i).name, "UTF-8");
                    }
                    mailMessage.addRecipients(Message.RecipientType.CC,
                            ccTo);
                }
                // 创建邮件的密送者地址,并设置到邮件消息中
                if (bcc.size() > 0) {
                    InternetAddress[] bccTo = new InternetAddress[bcc.size()];
                    for (int i = 0; i < bcc.size(); i++) {
                        String address;
                        if (bcc.get(i).address.contains("<") && bcc.get(i).address.contains(">")) {
                            address = bcc.get(i).address.split("<")[1].split(">")[0];
                        } else {
                            address = bcc.get(i).address;
                        }
                        bccTo[i] = new InternetAddress(address, to.get(i).name, "UTF-8");
                    }
                    mailMessage.addRecipients(Message.RecipientType.BCC,
                            bccTo);
                }
    
               /* mailMessage.setRecipient(Message.RecipientType.BCC,
                        new InternetAddress(bcc));*/
                // 设置邮件消息的主题
                mailMessage.setSubject(this.subject);
                // 设置邮件消息发送的时间
                mailMessage.setSentDate(new Date());
    
                MimeMultipart multipart = new MimeMultipart("mixed");
    
                BodyPart messageBodyPart = new MimeBodyPart();
                String htmlText = "<html><body><div>" + content + "</div></body></html>";
                messageBodyPart.setContent(htmlText, "text/html; charset=utf-8");
                multipart.addBodyPart(messageBodyPart);
    
                if (mFiles.size() > 0) {
                    String file;
                    for (int i = 0 ;i < mFiles.size() ; i++) {
                        file = mFiles.get(i);
                        MimeBodyPart imageBodyPart = new MimeBodyPart();
                        File imageFile = new File(file);
                        DataSource fds = new FileDataSource(imageFile);
                        imageBodyPart.setDataHandler(new DataHandler(fds));
                        String[] name = imageFile.getName().replace(" ","").split("\\.");
                        //由于我在保存附件的时候为了防止附件名称重复,在附件的名称前边加了邮箱的时间戳
                        // 所在在发送的时候要把前边的时间戳去掉
                        String filename = name[0].split(":")[name[0].split(":").length-1];
                        filename = filename.substring(2,filename.length()).replace("\\","");
                       //MimeUtility.encodeWord 防止附件名称中文乱码
                        imageBodyPart.setFileName(MimeUtility.encodeWord(filename+"." + name[name.length-1]));
                        String path ;
                         //UserAppConst.IS_SHOW_EMAIL_CID 这个判断可以自行去掉,我们暂时没有展示表情的需求,所以我做了个开关,暂时关掉了
                         if(UserAppConst.IS_SHOW_EMAIL_CID && mEmail != null) {
                            for(ATTACHMENT att : mEmail.attachment){
                                path = AppStoragePath.getCachePath() + File.separator + mEmail.time + att.realname;
                                if(path.equals(file) && !TextUtils.isEmpty(att.cid)){
                                    imageBodyPart.setContentID(att.cid.split(":")[1]);
                                }
                            }
                        }
    
                        multipart.addBodyPart(imageBodyPart);
    
                    }
                }
                mailMessage.setContent(multipart);
                // 发送邮件
                Transport.send(mailMessage);
                //保存到IMAP服务器发件箱
                copyIntoSent(mailMessage);
                //成功
                android.os.Message msg = new android.os.Message();
                msg.what = IMAPSentEmailActivity.SENT_SUCCESS;
                handler.sendMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
                //失败
                android.os.Message msg = new android.os.Message();
                msg.what = IMAPSentEmailActivity.SENT_FAILD;
                handler.sendMessage(msg);
            }
        }
    
    
        /**
         * 保存邮件到发件箱
         *
         * @param msg 邮件信息
         */
        private void copyIntoSent(Message msg) {
            IMAPStore store = null;
            IMAPFolder folder = null;
            try {
                Properties prop = System.getProperties();
                prop.put("mail.store.protocol", "imap");
                prop.put("mail.imap.host", this.host);
                prop.put("mail.imap.port", SESSION.getInstance().getEmailPost());
    
                Session session = Session.getDefaultInstance(prop);
    
    
                store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制,连接服务器
    
                store.connect(this.userName, this.password);
    
                folder = (IMAPFolder) store.getFolder("Sent");
                if (!folder.exists()) {
                    folder.create(Folder.HOLDS_MESSAGES);
                }
                folder.open(Folder.READ_WRITE);
                folder.appendMessages(new Message[]{msg});
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 判断发件文件夹是否打开如果打开则将其关闭
                if (folder != null && folder.isOpen()) {
                    try {
                        folder.close(true);
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                }
                // 判断邮箱存储是否打开如果打开则将其关闭
                if (store != null && store.isConnected()) {
                    try {
                        store.close();
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
    
    }
    

     注意 注意 注意 :此处一个超级大坑,如果附件名称太长,会在其他邮箱客户端获取不到附件名称,超级大坑啊,我只说解决办法:在application的初始化里边加上一行代码:

    System.setProperty("mail.mime.splitlongparameters","false");
    

    ok,这个也解决了,具体原因看我上一篇博客,有详细解释的。

    4、邮件正文显示表情

     上边注释说到,这个“附件”啊,其实并不是就是你发邮件时候附带的文件,他还包含你发送邮件时候正文里边夹杂的表情啊什么的。因为我们在获取附件的时候,已经全部都下载到本地了,这里展示表情等内嵌资源就会简单的多了,上代码。

     /**
         * 给文本嵌套css样式
         * 我这里为了让邮件正文看起来跟顺眼一点,外边加了css
         */
        private void setHtml() {
            String css = "<style type=\"text/css\">" +
                    "body {" +
                    "font-size:15px;"+
                    //允许自动换行(汉字网页应该不需要这一属性,这个用来强制英文单词换行,类似于word/wps中的西文换行)
                    "word-wrap:break-word;" +
                    "}" +
                    "</style>";
    
    
    
    
            String content = mEmail.content;
            if (UserAppConst.IS_SHOW_EMAIL_CID) {//此处判断,你们可以自行去掉,因为这个显示表情的需求暂时没有,所以我做了个开关,把他先给屏蔽了
                for (int i = 0; i < mEmail.attachment.size(); i++) {
                    if (!TextUtils.isEmpty(mEmail.attachment.get(i).cid) && content.contains(mEmail.attachment.get(i).cid)) {
                        content = content.replace(mEmail.attachment.get(i).cid, "file://" + AppStoragePath.getCachePath() + File.separator + mEmail.time + mEmail.attachment.get(i).realname);
                    }
                }
            }
            String html = "<html><header>" + css + "</header><body>" + content + "</body></html>";
        //    mContent.loadData(html, "text/html; charset=UTF-8", null);
            mContent.loadDataWithBaseURL(null,html,"text/html","UTF-8",null);
        }

    其实就是把邮箱正文中的 cid:85545245 换成附件的本地地址  file://.... 

    注意:这里一定要是file:// + 附件本地地址。

    总结,希望能帮到大家吧,有什么不足的地方还望大家指正,我写的这些也不是很好,比如附件怎么做到先不下载,想看的时候点击摸个附件的时候才下载并且打开呢,我还在思考中,好了今天就到这里了。

     

    展开全文
  • Domino 生成邮件到草稿

    千次阅读 2013-06-06 15:11:14
    相关架包下载地址: http://download.csdn.net/detail/qm4050/5531483 代码如下: import java.io.File; import lotus.domino.Database; import lotus.domino.Document; import lotus.domino.Item; ...

    相关架包下载地址:


    http://download.csdn.net/detail/qm4050/5531483


    代码如下:

    import java.io.File;
    import lotus.domino.Database;
    import lotus.domino.Document;
    import lotus.domino.Item;
    import lotus.domino.NotesException;
    import lotus.domino.NotesFactory;
    import lotus.domino.RichTextItem;
    import lotus.domino.Session;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class MailPDF {
    	private static final Logger log = LoggerFactory.getLogger(MailPDF.class);
    	private Session session;
    	private Database mailDb;
    	private static MailPDF instance = new MailPDF();
    
    	private MailPDF() {
    
    	}
    
    	/**
    	 * 构造器
    	 * 
    	 * @param server
    	 *            Domino Server IP Address or DNS
    	 * @param user
    	 *            who connect to Domino Server
    	 * @param password
    	 *            who's password
    	 * @param senderMailFile
    	 *            the mail file path relatived to <Domino>\Data directory.
    	 * @return the class instance.
    	 * @throws NotesException
    	 */
    	public static MailPDF create(String server, String user, String password, String senderMailFile)
    			throws NotesException {
    		if (instance.session == null || !instance.session.isValid()) {
    			instance.session = NotesFactory.createSession(server, user, password);
    		}
    		instance.mailDb = instance.session.getDatabase(null, senderMailFile);
    
    		return instance;
    	}
    
    	/**
    	 * 在特定用户处创建邮件
    	 * 
    	 * @param sender
    	 *            发件人
    	 * @param recipients
    	 *            收件人
    	 * @param cc
    	 *            抄送
    	 * @param bcc
    	 *            密送
    	 * @param body
    	 *            正文内容
    	 * @param pdfPath
    	 *            PDF文件全路径
    	 * @return 是否创建成功
    	 * @throws NotesException
    	 */
    	public boolean createDraftMail(String sender, String[] recipients, String[] cc, String[] bcc, String subject,
    			String[] body, String pdfPath) throws RuntimeException, NotesException {
    		if (session == null || !session.isValid()) {
    			throw new RuntimeException("No Notes Session");
    		}
    		if (sender == null || "".equals(sender)) {
    			throw new RuntimeException("Sender is Empty");
    		}
    		if (subject == null) {
    			throw new RuntimeException("Subject is Empty");
    		}
    		if (mailDb == null) {
    			throw new RuntimeException("Mail Database Open Failed.");
    		}
    		if (!mailDb.isOpen())
    			mailDb.open();
    
    		if (pdfPath == null || "".equals(pdfPath)) {
    			throw new RuntimeException("PDF file Not Found");
    		}
    
    		Document doc = mailDb.createDocument();
    		Item item;
    		doc.replaceItemValue("Form", "Memo");
    		doc.replaceItemValue("Subject", subject);
    		item = doc.replaceItemValue("EnterSendTo","");
    		for (String recipient : recipients) {
    			item.appendToTextList(recipient);
    		}
    		if (cc != null) {
    			item = doc.replaceItemValue("EnterCopyTo","");
    			for (String c : cc) {
    				item.appendToTextList(c);
    			}
    		}
    		if (bcc != null) {
    			item = doc.replaceItemValue("EnterBlindCopyTo","");
    			for (String bc : bcc) {
    				item.appendToTextList(bc);
    			}
    		}
    		RichTextItem rtItem = doc.createRichTextItem("Body");
    		if (body != null) {
    			for (String b : body) {
    				rtItem.appendText(b);
    				rtItem.addNewLine();
    			}
    		}
    		String pdfName = pdfPath.substring(pdfPath.lastIndexOf(File.separator) + File.separator.length());
    		rtItem.embedObject(1454, "", pdfPath, pdfName);
    		doc.computeWithForm(true, false);
    		doc.save();
    		return true;
    	}
    
    	public void close() {
    		try {
    			this.session.recycle();
    		} catch (NotesException e) {
    			log.error("", e);
    		}
    	}
    	
    	
    	public static void main(String[] args) {
    		try {
    			MailPDF mp = MailPDF.create("localhost", "username", "password", "mail/username.nsf");
    			mp.createDraftMail("username@demo.com", 
    					new String[] { "demo/demo", "demo@demo.com" }, 
    					new String[] {"demo/demo", "demo@demo.com" }, 
    					new String[] { "demo/demo", "demo@demo.com" }, 
    					"test",
    					new String[] { "test", "test" }, "D:/test.pdf");
    		} catch (NotesException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			System.out.println(e.text);
    		}
    	}
    
    }
    



    展开全文
  • 资源介绍:邮件群发协议软件 日发百万邮件不进垃圾 全网独家技术 无需发件人即可群发2句话组合为一句,暂无字数限制内容不能有数字和符号 可以用别的文字代替 可以发字母本软件接收邮件的帐号只支持一次性发送,若...
  • 文件名称: Java-mail下载 收藏√ [5 4 3 2 1]开发工具: Java文件大小: 2385 KB上传时间: 2014-12-25下载次数: 0提 供 者: 刘璨详细说明:java实现的一个邮件收发系统。可以绑定自己邮箱。能看收件,发送邮件,对...

    文件名称: Java-mail891ea1e7dab975064c6bfd22796603ae.gif下载

      收藏√  [443d104427974206832dc4b12407db70.gif

     5  4  3  2  1 fb9128a58cbeaabbeb3718ed75079ccf.gif]

    开发工具: Java

    文件大小: 2385 KB

    上传时间: 2014-12-25

    下载次数: 0

    提 供 者: 刘璨

    详细说明:java实现的一个邮件收发系统。可以绑定自己邮箱。能看收件箱,发送邮件,对邮箱进行管理等。-A mail system java implementation. You can bind your own mailbox. Can see the Inbox, Sent Items, for mailbox management.

    文件列表(点击判断是否您需要的文件,如果是垃圾请在下面评价投诉):

    Java邮件收发系统

    ................\.classpath

    ................\.project

    ................\email

    ................\.....\bll

    ................\.....\...\Mail.class

    ................\.....\...\Mail.java

    ................\.....\...\MailBLL.class

    ................\.....\...\MailBLL.java

    ................\.....\...\Recv.class

    ................\.....\...\Recv.java

    ................\.....\...\RecvOneMail.class

    ................\.....\...\Send.class

    ................\.....\...\Send.java

    ................\.....\...\TableMail.class

    ................\.....\...\TableMail.java

    ................\.....\dal

    ................\.....\...\DataBase.class

    ................\.....\...\DataBase.java

    ................\.....\...\FileTool.class

    ................\.....\...\FileTool.java

    ................\.....\factory

    ................\.....\.......\Factory.class

    ................\.....\.......\Factory.java

    ................\.....\.......\MYSQLFactory.class

    ................\.....\.......\MYSQLFactory.java

    ................\.....\UI

    ................\.....\..\MyImage.class

    ................\.....\..\MyImage.java

    ................\.....\..\SetUp.class

    ................\.....\..\SetUp.java

    ................\.....\..\Tree.class

    ................\.....\..\Tree.java

    ................\.....\..\TreeNode.class

    ................\.....\..\UI$Login.class

    ................\.....\..\UI$Menu.class

    ................\.....\..\UI$NoRead.class

    ................\.....\..\UI$NoRecvBox.class

    ................\.....\..\UI$RecvBox.class

    ................\.....\..\UI$Register.class

    ................\.....\..\UI$SendBox.class

    ................\.....\..\UI.class

    ................\.....\..\UI.java

    ................\image

    ................\.....\background1.png

    ................\.....\background2.png

    ................\.....\background3.png

    ................\.....\background4.png

    ................\.....\draft.png

    ................\.....\exist.png

    ................\.....\friends.png

    ................\.....\home.png

    ................\.....\login1.png

    ................\.....\login2.png

    ................\.....\login3.png

    ................\.....\noread.png

    ................\.....\receive.png

    ................\.....\search.png

    ................\.....\send.png

    ................\.....\title.png

    ................\.....\title1.png

    ................\.....\title2.png

    ................\.....\write.png

    ................\Jar

    ................\...\activation.jar

    ................\...\mail.jar

    ................\...\mysql-connector-java-5.1.26-bin.jar

    ................\Read_Me_First.txt

    输入关键字,在本站238万海量源码库中尽情搜索:

    帮助

    展开全文
  • 如果收件中的空间已用尽,但是您的电子邮件中的内容很重要,但是附件已经下载到磁盘上,可以删除以释放一些空间,该功能可能特别有用。 Gmail附件提取器是一个简单的工具,可让您从Gmail帐户中的电子邮件中提取...
  • 显示Gmail收件中未读邮件的数量。 您也可以单击按钮打开收件,并接收有关新电子邮件的通知。 您可以设置“安静时间”以消除在最忙碌的时间里的干扰,也可以暂时“无干扰”地享受番茄般的体验。 这是的衍生产品...
  • 2 遍历该邮箱收、发件中自某时间点以来的所有邮件,筛选出带有附件的所有邮件 3 下载其中除“txt”类型的所有附件。 用C#实现,我只粗知有个ews库是与它有关的,求具体代码和编程思路。谢谢!
  • pop3是不支持判断邮件是否为已读的,也就是说你不能直接从收件里面取到未读邮件,这需要自己进行判断,然而imap就提供了这样的功能,使用imap时可以很轻松的判断该邮件是否为已读或未读或其他。   此外收件中...
  • 360断网急救独立版下载,修复网络无法连接的问题。 很多时候电脑除了问题我们都能上网搜索一下,很快就能解决问题,但如果网络出了问题,在断网的情况下就无法获得来自网络的帮助,这个时候360断网急救独立版就...
  • 这篇文章主要为大家详细介绍了PHP receiveMail实现收邮件功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下用PHP来发邮件,相信大家都不陌生,但读取收件的话,接触就少了,这次总结下自己的经验,希望可以帮助...
  • 注意:1.PHP读取收件主要是利用imap扩展,所以在使用以下方法前,必须开启imap扩展模块的支持.2.此方法支持中文,不会乱码,需要保持所有文件的编码的一致性1.文件结构2.邮件类 ./mailreceived/receiveMail....
  • 这篇文章主要为大家详细介绍了PHP receiveMail实现收邮件功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下用PHP来发邮件,相信大家都不陌生,但读取收件的话,接触就少了,这次总结下自己的经验,希望可以帮助...
  • WPS版方方格子工具是一款支持WPS使用的表格增强插件,包含方方格子工具、审计、图片、邮件、公式向导工具和汇总大师全套工具,拥有常用的文本处理、编辑、工作表、数据分析、视图工具、收纳、汇总拆分、打印、...
  • 你将作业要求发到了班级群里面,但是很多同学可能没有及时查看群消息,为了稳妥起见,你觉得有必要给班级同学们发封邮件告知(假设这个方法有效),作为学习python的你一定不会把收件人的地址一个一个复制到收件中,...
  • javaweb邮件管理系统

    2018-07-19 17:16:37
    邮件收发管理系统基于Java Web开发技术主要实现了用户的注册登录、个人信息管理、收发邮件、个人邮箱管理(收件、发件、草稿管理)、通讯录管理、文件上传与下载等功能,使用springmvc框架以及jsp+servlet...
  • 【实例简介】该邮件收发管理系统基于Java Web开发技术主要实现了用户的注册登录、个人信息管理、收发邮件、个人邮箱管理(收件、发件、草稿管理)、通讯录管理、文件上传与下载等功能,使用springmvc框架以及jsp...
  • FoxMail 7.2.12.322官网版软件大小:41.13 MB授权方式:免费软件...垃圾邮件会被自动分捡到垃圾邮件箱中,有效地降低垃圾邮件对用户干扰,较大限度地减少用户因为处理垃圾邮件而浪费的时间。数字签名和加密功能在Fo...
  • 将网页上的未读邮件,放入垃圾,再来新的邮件就能收取了。 转载于:https://www.cnblogs.com/DDSys/p/3198243.html
  • 含审计、图片、邮件、公式向导工具、Excel汇总大师。软件说明软件安装后,方方格子提供以下功能:常用的文本处理、编辑、工作表、数据分析、视图工具、收纳、汇总拆分、打印、图片、姓名、身份证工...
  • C++ 邮件推送 (smtp+libcurl+openssl)openssl 编译Libcurl 编译Smtp邮件推送项目于中需要一个邮件定时推送功能,准备用smtp实现本文中所有资源提供下载可编译源码+编译相关环境...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 384
精华内容 153
关键字:

下载邮件箱