我尝试了很多搜索,最终在这里提问。
我需要编写一段代码来从我的GMail中下载附件。我应该如何做?
到目前为止,我已经能够读取/发送电子邮件。但仍在尝试弄清如何下载附件。任何帮助都将不胜感激。
我需要编写一段代码来从我的GMail中下载附件。我应该如何做?
到目前为止,我已经能够读取/发送电子邮件。但仍在尝试弄清如何下载附件。任何帮助都将不胜感激。
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;
}