use of org.apache.commons.net.pop3.POP3MessageInfo in project gerrit by GerritCodeReview.
the class Pop3MailReceiver method handleEmails.
/**
* Opens a connection to the mail server, removes emails where deletion is pending, reads new
* email and closes the connection.
*
* @param async determines if processing messages should happen asynchronously
* @throws MailTransferException in case of a known transport failure
* @throws IOException in case of a low-level transport failure
*/
@Override
public synchronized void handleEmails(boolean async) throws MailTransferException, IOException {
POP3Client pop3;
if (mailSettings.encryption != Encryption.NONE) {
pop3 = new POP3SClient(mailSettings.encryption.name(), true);
} else {
pop3 = new POP3Client();
}
if (mailSettings.port > 0) {
pop3.setDefaultPort(mailSettings.port);
}
pop3.connect(mailSettings.host);
try {
if (!pop3.login(mailSettings.username, mailSettings.password)) {
throw new MailTransferException("Could not login to POP3 email server. Check username and password");
}
try {
POP3MessageInfo[] messages = pop3.listMessages();
if (messages == null) {
throw new MailTransferException("Could not retrieve message list via POP3");
}
logger.atInfo().log("Received %d messages via POP3", messages.length);
// Fetch messages
List<MailMessage> mailMessages = new ArrayList<>();
for (POP3MessageInfo msginfo : messages) {
if (msginfo == null) {
// Message was deleted
continue;
}
try (BufferedReader reader = (BufferedReader) pop3.retrieveMessage(msginfo.number)) {
if (reader == null) {
throw new MailTransferException("Could not retrieve POP3 message header for message " + msginfo.identifier);
}
int[] message = fetchMessage(reader);
MailMessage mailMessage = RawMailParser.parse(message);
// 822 and delete the message if deletion is pending.
if (pendingDeletion.contains(mailMessage.id())) {
if (pop3.deleteMessage(msginfo.number)) {
pendingDeletion.remove(mailMessage.id());
} else {
logger.atSevere().log("Could not delete message %d", msginfo.number);
}
} else {
// Process message further
mailMessages.add(mailMessage);
}
} catch (MailParsingException e) {
logger.atSevere().log("Could not parse message %d", msginfo.number);
}
}
dispatchMailProcessor(mailMessages, async);
} finally {
pop3.logout();
}
} finally {
pop3.disconnect();
}
}
Aggregations