This site is currently read-only as we are migrating to Oracle Forums for an improved community experience. You will not be able to initiate activity until January 30th, when you will be able to use this site as normal.

    Forum Stats

  • 3,890,308 Users
  • 2,269,776 Discussions
  • 7,916,824 Comments

Discussions

About backup mail in eml format

user4074040
user4074040 Member Posts: 3 Blue Ribbon

Hi,

I want to use javamail to backup my email account and save it in eml format. but my programme always throw an error: "error loading POP3 headers" when it has saved several mails. the code may have some problems. What is the reason and how to resolve the problem? The follow code is my programme:

public void loadMailListFromServer() {

Properties props = System.getProperties();

props.setProperty("mail.store.protocol", "pop3");

     props.setProperty("mail.pop3.host", "pop.qq.com");

     props.setProperty("mail.pop3.port", "995");

     props.setProperty("mail.pop3.ssl.enable", "true");

     props.put("mail.debug", "false"); 

       Session session = Session.getDefaultInstance(props, new Authenticator(){

       public PasswordAuthentication getPasswordAuthentication() {

          return new PasswordAuthentication("[email protected]", "MY_PASSWORD");

       }

     });

     

    try {

    Store store = session.getStore("pop3"); 

    store.connect(); 

    Folder folder   = store.getFolder("INBOX");

    folder.open(Folder.READ_ONLY);

    int total = folder.getMessageCount();

    for(int i=1; i<=total; i++) {

     try {

     MimeMessage msg = (MimeMessage)folder.getMessage(i);

     loadMail(session, i, msg);

     } catch(Exception e) {

     e.printStackTrace();

     System.out.println("exception and reset...");

     if(!store.isConnected()) {

     store.close();

     }

     if(folder.isOpen()) folder.close();

     store = session.getStore("pop3");

     store.connect();

     folder = store.getFolder("INBOX");

     folder.open(Folder.READ_ONLY);

     total = folder.getMessageCount();

     i--;

     }

    }

    store.close();

    } catch(Exception e) {

     e.printStackTrace();

    }

}

protected void loadMail(Session session, int messageNo, MimeMessage message) throws Exception {

  

   SimpleDateFormat sdtf   = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   SimpleDateFormat sdf   = new SimpleDateFormat("yyyy-MM-dd");

  

   String    subject   = message.getSubject();

Date     recvDate  = message.getSentDate();

String    messageId  = message.getMessageID();

String    uid     = UUID.randomUUID().toString();

File     dir     = new File("D:/mail_backup/");

File     file    = new File(String.format("D:/mail_backup/%s.eml", uid));

if(!dir.exists()) dir.mkdirs();

if(!file.exists()) dir.createNewFile();

OutputStream ips  = new FileOutputStream(file);

message.writeTo(ips);

ips.close();

System.out.println(sdtf.format(recvDate) + " mail subject:"

+ subject + "|messageID="+ messageId);

}

Tagged: