In previous post am mention about how download mails from gmail server
than new question occurs how download all mail from all folder like spam, important, sent, draft etc
first need to list out all folder exist in your mail account by this
output some thing like this
and than extract all mail from the folder and same mail in eml format see below code
than new question occurs how download all mail from all folder like spam, important, sent, draft etc
first need to list out all folder exist in your mail account by this
Folder[] folder = store.getDefaultFolder().list("*");
output some thing like this
INBOX Notes Personal Receipts Travel Work [Gmail]/All Mail [Gmail]/Drafts [Gmail]/Important [Gmail]/Sent Mail [Gmail]/Spam [Gmail]/Starred [Gmail]/Trash
and than extract all mail from the folder and same mail in eml format see below code
import java.io.File; import java.io.FileOutputStream; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Store; public class test { public static long start; public static void main(String args[]) throws Exception { Store store = null; Folder[] folder = null; try { start = System.currentTimeMillis(); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); Session session = Session.getDefaultInstance(props, null); session.setDebug(true); store = session.getStore("imaps"); store.connect("imap.gmail.com", "--mail id--", "--password--"); folder = store.getDefaultFolder().list("*"); for (javax.mail.Folder folder1 : folder) { if ((folder1.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) { System.out.println(folder1.getFullName() + ": " + folder1.getMessageCount()); folder1.open(Folder.READ_ONLY); for(Message msg : folder1.getMessages()){ File ff = new File("C:/Desktop/mails", "msg/"+folder1.getFullName()); if(!ff.exists()) ff.mkdirs(); File emlFile = new File(ff.getAbsolutePath()+System.getProperty("file.separator")+msg.getHeader("message-id")[0].replace("<", "").replace(">", "")+".eml"); emlFile.createNewFile(); msg.writeTo(new FileOutputStream(emlFile)); } if (folder1 != null) { try { folder1.close(true); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { if (store != null) { try { store.close(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } long end = System.currentTimeMillis() - start; System.out.println("--- Done: , end: " + end + "ms"); } } }
No comments:
Post a Comment