在android程序中下载gmail附件

时间:2013-05-29 06:07:51

标签: android email-attachments

我试了很多,最后在这里问。

我需要在 GMail 中为下载附件编写代码。我怎么能这样做?

直到现在我能够阅读/发送电子邮件。但仍然在弄清楚如何下载附件。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

附件不单独下载。它们是MIME多部分文档的一部分。您可以使用MimeMultipart类来解压缩它们。

答案 1 :(得分:0)

我做到了这一点。发布解决方案,以便其他人可以使用:

    protected Integer doInBackground(Void... vd){
            Properties props = new Properties();
            props.setProperty("mail.store.protocol", "imaps");
            props.setProperty("mail.imaps.host", "imaps.gmail.com");
            props.setProperty("mail.imaps.port", "993");
            props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.imaps.socketFactory.fallback", "false");
            Session s = Session.getInstance(props);
            sb = new StringBuilder();
            try{
                    store = s.getStore("imaps");
                    store.connect("imap.gmail.com", "youremailid@gmail.com", "password");
                    Folder inbox = store.getFolder("Inbox"); //Any folder name
                    inbox.open(Folder.READ_ONLY);
                    msgs = inbox.getMessages();
                    m=(Multipart)msgs[inbox.getMessageCount()-1].getContent(); //Getting the newest email. Assuming it has one attachment.
                    for(int i=0;i<m.getCount();i++){
                            bp = m.getBodyPart(i);
                            disposition = bp.getDisposition();
                            if(disposition!=null && (disposition.equals("ATTACHMENT"))){
                                    fileName = bp.getFileName();
                                    base64dec = (InputStream)bp.getContent();
                                    OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+fileName);
                                    byte data[] = new byte[8192];
                                    long total = 0;
                                    while ((count = base64dec.read(data)) != -1){
                                            total += count;
                                            output.write(data, 0, count);
                                            publishProgress((int)total);
                                    }
                                    output.flush();
                                    output.close();base64dec.close();
                            }
                    }
            }catch(Exception e){
                    errorMsg += "\nError: "+e.toString();
                    Log.e("MyError:",e.toString());
            }
            return 0;
    }