final MailAccountConfig cfg = ConfigXml.getInstance().getMebMailAccount();
if (cfg == null || cfg.getHostname() == null) {
// No mail account configured.
return 0;
}
final MailAccount mailAccount = new MailAccount(cfg);
try {
// If mark messages as seen is set then open mbox read-write.
mailAccount.connect("INBOX", markRecentMailsAsSeen);
final Mail[] mails = mailAccount.getMails(filter);
if (mails != null) {
for (final Mail mail : mails) {
final MebEntryDO entry = new MebEntryDO();
entry.setDate(mail.getDate());
final String content = mail.getContent();
final BufferedReader reader = new BufferedReader(new StringReader(content.trim()));
try {
StringBuffer buf = null;
while (reader.ready() == true) {
final String line = reader.readLine();
if (line == null) {
break;
}
if (line.startsWith("date=") == true) {
if (line.length() > 5) {
final String dateString = line.substring(5);
final Date date = MebDao.parseDate(dateString);
entry.setDate(date);
}
} else if (line.startsWith("sender=") == true) {
if (line.length() > 7) {
final String sender = line.substring(7);
entry.setSender(sender);
}
} else if (line.startsWith("msg=") == true) {
if (line.length() > 4) {
final String msg = line.substring(4);
buf = new StringBuffer();
buf.append(msg);
}
} else if (buf != null) {
buf.append(line);
} else {
entry.setSender(line); // First row is the sender.
buf = new StringBuffer(); // The message follows.
}
}
if (buf != null) {
entry.setMessage(buf.toString().trim());
}
} catch (IOException ex) {
log.fatal("Exception encountered " + ex, ex);
}
if (mebDao.checkAndAddEntry(entry, "MAIL") == true) {
counter++;
}
if (markRecentMailsAsSeen == true) {
try {
mail.getMessage().setFlag(Flags.Flag.SEEN, true);
//mail.getMessage().saveChanges();
} catch (MessagingException ex) {
log.error("Exception encountered while setting message flag SEEN as true: " + ex, ex);
}
}
// log.info(mail);
}
}
return counter;
} finally {
mailAccount.disconnect();
}
}