This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new f927899adce9 CAMEL-27531: camel-mail - mark the mail of an exchange 
that completes after the poll, and never another one (#30914)
f927899adce9 is described below

commit f927899adce9886844243573395e43583421f830
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 15:09:49 2026 +0530

    CAMEL-27531: camel-mail - mark the mail of an exchange that completes after 
the poll, and never another one (#30914)
    
    With pollEnrich or a ConsumerTemplate the exchange of a mail completes 
after the
    poll, while the poll thread closes the folder, disconnects or connects 
again:
    - with disconnect=true (or a re-created connection) onComplete failed with a
      NullPointerException on the null folder: the mail was never marked and its
      idempotent key stayed added;
    - processCommit opened the folder again after mailToCommit had checked the 
mail
      object, and marked it by its stale message number, which after an expunge 
is
      another mail (marked SEEN, or DELETED and expunged without being routed);
    - a mark that failed left the idempotent key added;
    - an exchange that completed after the consumer was stopped opened the 
folder
      again: IMAPStore logs in again with the credentials the closed store 
kept, so
      the stopped consumer marked the mail and left a connection open.
    
    The poll now connects and opens the folder, and closes it and disconnects, 
while
    holding a lock of the consumer; the completion checks and marks the mail 
while
    holding the same lock, and doStop closes the folder and the store while 
holding
    it. The lock is never held while a mail is routed. A completion that finds 
no
    folder connects again, finds the mail by its UID (IMAP) or key (POP3) and
    disconnects again with disconnect=true. A completion after the consumer 
stopped
    does not open the folder or connect: the mail is not marked and its key is
    settled. A poll that is running when the consumer stops does not log in 
again
    either: it checks the stop under the lock before it connects, and before it
    reads the message count and the UIDVALIDITY (on a closed IMAP folder both 
send
    a STATUS through the closed store, which logs in again); its later calls on 
the
    closed folder fail without connecting. processCommit no longer opens an IMAP
    folder again for a checked mail object (a folder closed in between means the
    mail is not marked), catches IllegalStateException too, and settles the key 
as
    on commit whenever the mail is not marked, as mailToCommit does.
    
    Review:
    - report commit errors after releasing the folder lock, upgrade guide entry
    - report a recorded commit error also when the commit then throws
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../apache/camel/component/mail/MailConsumer.java  | 351 ++++++++++++++++-----
 .../mail/MailConsumerAsyncCommitStressTest.java    | 142 +++++++++
 .../MailConsumerCommitAfterDisconnectTest.java     | 165 ++++++++++
 .../mail/MailConsumerCommitAfterStopTest.java      | 251 +++++++++++++++
 .../MailConsumerCommitErrorWithoutLockTest.java    | 161 ++++++++++
 .../mail/MailConsumerCommitFailedKeyTest.java      | 114 +++++++
 .../MailConsumerCommitWhileFolderClosesTest.java   | 286 +++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  20 ++
 8 files changed, 1404 insertions(+), 86 deletions(-)

diff --git 
a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java
 
b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java
index fe48fdc82ba7..32ac339c5e6c 100644
--- 
a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java
+++ 
b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java
@@ -25,10 +25,12 @@ import java.util.List;
 import java.util.Map;
 import java.util.Queue;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReentrantLock;
 
 import jakarta.mail.FetchProfile;
 import jakarta.mail.Flags;
 import jakarta.mail.Folder;
+import jakarta.mail.FolderClosedException;
 import jakarta.mail.FolderNotFoundException;
 import jakarta.mail.Message;
 import jakarta.mail.MessageRemovedException;
@@ -70,6 +72,19 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
     private static final Logger LOG = 
LoggerFactory.getLogger(MailConsumer.class);
 
     private final JavaMailSender sender;
+    // the poll connects, opens the folder, closes it and disconnects (folder 
and store are set or nulled) while holding
+    // folderLock, and an exchange that completes on another thread than the 
poll (pollEnrich, ConsumerTemplate) marks
+    // its mail while holding it, so a mail is checked and marked against one 
open of the folder. It is never held while
+    // a mail is routed: the completion of a mail routed by the poll thread 
takes it too, and passes the errors of the
+    // mark to the exception handler (which routes them with 
bridgeErrorHandler=true) after it released it. doStop
+    // closes the folder and the store while holding it
+    private final ReentrantLock folderLock = new ReentrantLock();
+    // the errors of marking a mail found while holding folderLock, passed to 
the exception handler by commit after it
+    // released the lock. Guarded by folderLock
+    private final List<CommitError> commitErrors = new ArrayList<>();
+    // set by doStop and cleared by doStart, while holding folderLock: a poll 
that was already running when the consumer
+    // stopped does not connect again, and does not ask the server for the 
message count or the UIDVALIDITY
+    private boolean closed;
     private Folder folder;
     private Store store;
     private boolean skipFailedMessage;
@@ -82,8 +97,8 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
     // the IMAP UIDs of the mails of the current poll, and the UIDVALIDITY of 
the folder when they were retrieved
     private final Map<Message, Long> batchUids = new IdentityHashMap<>();
     private volatile long batchUidValidity = -1;
-    // the open of the folder in which the mails of the current poll were 
retrieved, read before they are retrieved: an
-    // exchange completing on another thread can open the folder again while 
they are retrieved
+    // the open of the folder in which the mails of the current poll were 
retrieved, read with the message count before
+    // they are retrieved: an exchange completing on another thread can open 
the folder again while they are retrieved
     private int batchFolderOpen;
 
     /**
@@ -98,16 +113,31 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
 
     @Override
     protected void doStart() throws Exception {
+        folderLock.lock();
+        try {
+            closed = false;
+        } finally {
+            folderLock.unlock();
+        }
         super.doStart();
     }
 
     @Override
     protected void doStop() throws Exception {
-        if (folder != null && folder.isOpen()) {
-            folder.close(true);
-        }
-        if (store != null && store.isConnected()) {
-            store.close();
+        // close while no poll connects or closes and no completing exchange 
marks its mail. Afterwards neither opens the
+        // folder nor connects again (commit checks isRunAllowed, the poll 
checks closed): IMAPStore would log in again
+        // with the credentials the closed store kept, and nobody would close 
that connection
+        folderLock.lock();
+        try {
+            closed = true;
+            if (folder != null && folder.isOpen()) {
+                folder.close(true);
+            }
+            if (store != null && store.isConnected()) {
+                store.close();
+            }
+        } finally {
+            folderLock.unlock();
         }
 
         super.doStop();
@@ -141,47 +171,75 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
         pendingExchanges = 0;
         int polledMessages = 0;
 
-        ensureIsConnected();
-
-        if (store == null || folder == null) {
-            throw new IllegalStateException(
-                    "MailConsumer did not connect properly to the MailStore: "
-                                            + 
getEndpoint().getConfiguration().getMailStoreLogInformation());
-        }
+        // connect and open the folder while no exchange of an earlier poll 
marks its mail
+        folderLock.lock();
+        try {
+            if (closed) {
+                LOG.debug("The consumer of {} was stopped while it started to 
poll: not connecting again",
+                        
getEndpoint().getConfiguration().getMailStoreLogInformation());
+                return 0;
+            }
+            ensureIsConnected();
 
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Polling mailbox folder: {}", 
getEndpoint().getConfiguration().getMailStoreLogInformation());
-        }
+            if (store == null || folder == null) {
+                throw new IllegalStateException(
+                        "MailConsumer did not connect properly to the 
MailStore: "
+                                                + 
getEndpoint().getConfiguration().getMailStoreLogInformation());
+            }
 
-        if (getEndpoint().getConfiguration().getFetchSize() == 0) {
-            LOG.warn(
-                    "Fetch size is 0 meaning the configuration is set to poll 
no new messages at all. Camel will skip this poll.");
-            return 0;
-        }
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Polling mailbox folder: {}", 
getEndpoint().getConfiguration().getMailStoreLogInformation());
+            }
 
-        // ensure folder is open
-        try {
-            if (!folder.isOpen()) {
-                openFolder();
+            if (getEndpoint().getConfiguration().getFetchSize() == 0) {
+                LOG.warn(
+                        "Fetch size is 0 meaning the configuration is set to 
poll no new messages at all. Camel will skip this poll.");
+                return 0;
             }
-        } catch (MessagingException e) {
-            // some kind of connectivity error, so lets re-create connection
-            String msg = "Error opening mail folder due to " + e.getMessage() 
+ ". Will re-create connection on next poll.";
-            LOG.warn(msg);
-            if (LOG.isDebugEnabled()) {
-                LOG.debug(msg, e);
+
+            // ensure folder is open
+            try {
+                if (!folder.isOpen()) {
+                    openFolder();
+                }
+            } catch (MessagingException e) {
+                // some kind of connectivity error, so lets re-create 
connection
+                String msg = "Error opening mail folder due to " + 
e.getMessage() + ". Will re-create connection on next poll.";
+                LOG.warn(msg);
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug(msg, e);
+                }
+                disconnect();
+                return 0; // return since we cannot poll mail messages, but 
will re-connect on next poll.
             }
-            disconnect();
-            return 0; // return since we cannot poll mail messages, but will 
re-connect on next poll.
+        } finally {
+            folderLock.unlock();
         }
 
         // okay consumer is connected to the mail server
         forceConsumerAsReady();
 
         try {
-            int count = folder.getMessageCount();
+            int count;
+            // read the message count and the UIDVALIDITY of this open while 
doStop cannot close the folder: on a closed
+            // IMAP folder both ask the server through the store (STATUS), 
which logs in again with the credentials the
+            // closed store kept, and nobody would close that connection. The 
calls on the folder that follow fail on a
+            // closed folder instead (they check that it is open)
+            folderLock.lock();
+            try {
+                if (closed) {
+                    LOG.debug("The consumer of {} was stopped while it polled: 
not reading the folder",
+                            
getEndpoint().getConfiguration().getMailStoreLogInformation());
+                    return 0;
+                }
+                count = folder.getMessageCount();
+                batchFolderOpen = folderOpens.get();
+                batchUidValidity = readUidValidity();
+            } finally {
+                folderLock.unlock();
+            }
             if (count > 0) {
-                Queue<Exchange> messages = retrieveMessages();
+                Queue<Exchange> messages = retrieveMessages(count);
                 polledMessages = processBatch(CastUtils.cast(messages));
 
                 final MailBoxPostProcessAction postProcessor = 
getEndpoint().getPostProcessAction();
@@ -194,32 +252,41 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
         } catch (Exception e) {
             handleException(e);
         } finally {
-            // need to ensure we release resources, but only if closeFolder or 
disconnect = true
-            if (getEndpoint().getConfiguration().isCloseFolder() || 
getEndpoint().getConfiguration().isDisconnect()) {
-                try {
-                    if (folder != null && folder.isOpen()) {
-                        if (LOG.isDebugEnabled()) {
-                            LOG.debug("Close mailbox folder {} from {}", 
folder.getName(),
-                                    
getEndpoint().getConfiguration().getMailStoreLogInformation());
-                        }
-                        folder.close(true);
-                    }
-                } catch (Exception e) {
-                    // some mail servers will lock the folder so we ignore in 
this case (CAMEL-1263)
-                    LOG.debug("Could not close mailbox folder: {}. This 
exception is ignored.", folder.getName(), e);
+            // close and disconnect while no exchange that completes on 
another thread marks its mail: it marks it
+            // before (the folder is still open) or after (it opens the folder 
again, or connects again)
+            folderLock.lock();
+            try {
+                // need to ensure we release resources, but only if 
closeFolder or disconnect = true
+                if (getEndpoint().getConfiguration().isCloseFolder() || 
getEndpoint().getConfiguration().isDisconnect()) {
+                    closeFolder();
                 }
+                // should we disconnect, the header can override the 
configuration
+                if (getEndpoint().getConfiguration().isDisconnect()) {
+                    disconnect();
+                }
+            } finally {
+                folderLock.unlock();
             }
         }
 
-        // should we disconnect, the header can override the configuration
-        boolean disconnect = getEndpoint().getConfiguration().isDisconnect();
-        if (disconnect) {
-            disconnect();
-        }
-
         return polledMessages;
     }
 
+    private void closeFolder() {
+        try {
+            if (folder != null && folder.isOpen()) {
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Close mailbox folder {} from {}", 
folder.getName(),
+                            
getEndpoint().getConfiguration().getMailStoreLogInformation());
+                }
+                folder.close(true);
+            }
+        } catch (Exception e) {
+            // some mail servers will lock the folder so we ignore in this 
case (CAMEL-1263)
+            LOG.debug("Could not close mailbox folder: {}. This exception is 
ignored.", folder.getName(), e);
+        }
+    }
+
     private void disconnect() {
         if (LOG.isDebugEnabled()) {
             LOG.debug("Disconnecting from {}", 
getEndpoint().getConfiguration().getMailStoreLogInformation());
@@ -280,10 +347,7 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
             exchange.getExchangeExtension().addOnCompletion(new 
SynchronizationAdapter() {
                 @Override
                 public void onComplete(Exchange exchange) {
-                    Message current = mailToCommit(mail, uid, uidValidity, 
batchOpen, exchange);
-                    if (current != null) {
-                        processCommit(current, exchange);
-                    }
+                    commit(mail, uid, uidValidity, batchOpen, exchange);
                 }
 
                 @Override
@@ -340,6 +404,105 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
         folderOpens.incrementAndGet();
     }
 
+    /**
+     * Marks the mail of an exchange that completed. The mail is checked and 
marked under the folder lock, so the poll
+     * cannot close the folder, disconnect or connect again in between. With 
pollEnrich or a ConsumerTemplate the
+     * exchange completes after the poll, which may have disconnected 
meanwhile (disconnect=true, or the folder could
+     * not be opened): the consumer then connects again to mark the mail, 
which is found again by its UID (IMAP) or its
+     * key (POP3) as after any other new open of the folder, and disconnects 
again with disconnect=true. When the
+     * consumer is stopped, the mail is not marked and its idempotent key is 
settled as on commit: nothing opens the
+     * folder or connects after a stop. An error of the mark is passed to the 
exception handler after the lock is
+     * released: with bridgeErrorHandler=true the handler routes it, and the 
next poll and doStop must not wait for
+     * that. The error is passed also when settling the idempotent key then 
throws (an idempotentRepository that is
+     * down): that exception is thrown once the recorded error was passed.
+     */
+    void commit(Message mail, Long uid, long uidValidity, int batchOpen, 
Exchange exchange) {
+        List<CommitError> errors;
+        RuntimeException failure = null;
+        folderLock.lock();
+        try {
+            commitLocked(mail, uid, uidValidity, batchOpen, exchange);
+        } catch (RuntimeException e) {
+            failure = e;
+        } finally {
+            errors = new ArrayList<>(commitErrors);
+            commitErrors.clear();
+            folderLock.unlock();
+        }
+        for (CommitError error : errors) {
+            getExceptionHandler().handleException(error.message(), 
error.exchange(), error.cause());
+        }
+        if (failure != null) {
+            throw failure;
+        }
+    }
+
+    private void commitLocked(Message mail, Long uid, long uidValidity, int 
batchOpen, Exchange exchange) {
+        if (!isRunAllowed()) {
+            // doStop closed the folder and the store (or closes them once 
this returns): opening the folder or
+            // connecting here would log in again and leave that connection 
open
+            LOG.warn("The consumer of {} is stopped: the mail of an exchange 
that completed after the consumer stopped"
+                     + " is not marked as {}.",
+                    
getEndpoint().getConfiguration().getMailStoreLogInformation(),
+                    getEndpoint().getConfiguration().isDelete() ? "DELETED" : 
"SEEN");
+            commitIdempotentKey((String) 
exchange.removeProperty(MAIL_MESSAGE_UID));
+            return;
+        }
+        boolean connected = false;
+        if (folder == null) {
+            if (!connectToCommit(mail, exchange)) {
+                return;
+            }
+            connected = true;
+        }
+        try {
+            Message current = mailToCommit(mail, uid, uidValidity, batchOpen, 
exchange);
+            if (current != null) {
+                processCommit(current, exchange);
+            }
+        } finally {
+            if (connected && getEndpoint().getConfiguration().isDisconnect()) {
+                closeFolder();
+                disconnect();
+            }
+        }
+    }
+
+    /**
+     * Reports an error of marking a mail. While holding the folder lock (in 
{@link #commit}), the error is recorded and
+     * commit passes it to the exception handler once it released the lock.
+     */
+    private void handleCommitException(Message mail, Exchange exchange, 
Throwable cause) {
+        String message = "Error occurred during committing mail message: " + 
mail;
+        if (folderLock.isHeldByCurrentThread()) {
+            commitErrors.add(new CommitError(message, exchange, cause));
+        } else {
+            getExceptionHandler().handleException(message, exchange, cause);
+        }
+    }
+
+    private record CommitError(String message, Exchange exchange, Throwable 
cause) {
+    }
+
+    /**
+     * Connects again to mark the mail of an exchange that completed after the 
poll disconnected. Returns false when the
+     * consumer cannot connect: the mail is then not marked, and its 
idempotent key is settled as on commit.
+     */
+    private boolean connectToCommit(Message mail, Exchange exchange) {
+        LOG.debug("Connecting to {} again to mark the mail of an exchange that 
completed after the poll disconnected",
+                getEndpoint().getConfiguration().getMailStoreLogInformation());
+        try {
+            ensureIsConnected();
+            return true;
+        } catch (Exception e) {
+            handleCommitException(mail, exchange, e);
+            commitIdempotentKey((String) 
exchange.removeProperty(MAIL_MESSAGE_UID));
+            // the store may be connected without the folder: the next poll 
connects again
+            disconnect();
+            return false;
+        }
+    }
+
     /**
      * The mail to mark once its exchange completed. When the folder was 
opened again since the mail was retrieved (its
      * connection dropped while the mail was routed), the mail object of the 
poll is stale: for IMAP, the mail is looked
@@ -380,7 +543,7 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
         } catch (MessagingException | IllegalStateException e) {
             // IllegalStateException: the poll thread opened or closed the 
folder (closeFolder=true) at the same time
             // (IMAPFolder checkClosed / checkOpened)
-            getExceptionHandler().handleException("Error occurred during 
committing mail message: " + mail, exchange, e);
+            handleCommitException(mail, exchange, e);
             // the mail is not marked: settle its key as on commit, so it is 
not skipped as a duplicate for good
             commitIdempotentKey((String) 
exchange.removeProperty(MAIL_MESSAGE_UID));
             return null;
@@ -392,8 +555,7 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
      * so a mail can be found again when the folder had to be opened again 
before the mail is marked.
      */
     private void rememberUids(Queue<Exchange> batch) {
-        if (batch.isEmpty() || !(folder instanceof UIDFolder uidFolder)
-                || 
getEndpoint().getConfiguration().getProtocol().startsWith("pop3")) {
+        if (batch.isEmpty() || batchUidValidity < 0 || !(folder instanceof 
UIDFolder uidFolder)) {
             return;
         }
         List<Message> mails = new ArrayList<>(batch.size());
@@ -404,7 +566,6 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
             FetchProfile profile = new FetchProfile();
             profile.add(UIDFolder.FetchProfileItem.UID);
             folder.fetch(mails.toArray(new Message[0]), profile);
-            batchUidValidity = uidFolder.getUIDValidity();
             for (Message mail : mails) {
                 batchUids.put(mail, uidFolder.getUID(mail));
             }
@@ -414,6 +575,23 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
         }
     }
 
+    /**
+     * The UIDVALIDITY of the open IMAP folder (JavaMail keeps it from the 
select), or -1 for POP3 or when it cannot be
+     * read: the UIDs of the mails of the poll are then not remembered. Called 
while holding the folder lock, before the
+     * mails are retrieved.
+     */
+    private long readUidValidity() {
+        if (!(folder instanceof UIDFolder uidFolder) || 
getEndpoint().getConfiguration().getProtocol().startsWith("pop3")) {
+            return -1;
+        }
+        try {
+            return uidFolder.getUIDValidity();
+        } catch (MessagingException e) {
+            LOG.debug("Cannot get the UIDVALIDITY of folder {}. This exception 
is ignored.", folder.getFullName(), e);
+            return -1;
+        }
+    }
+
     /**
      * Settles the idempotent key of a mail whose exchange completed, as 
processCommit does.
      */
@@ -456,13 +634,13 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
     }
 
     /**
+     * @param  count              the message count of the folder, read by the 
poll while holding the folder lock
      * @return                    Messages from input folder according to the 
search and sort criteria stored in the
      *                            endpoint
      * @throws MessagingException If message retrieval fails
      */
-    private Queue<Exchange> retrieveMessages() throws MessagingException {
+    private Queue<Exchange> retrieveMessages(int count) throws 
MessagingException {
         Queue<Exchange> answer = new LinkedList<>();
-        batchFolderOpen = folderOpens.get();
 
         Message[] messages;
         final SortTerm[] sortTerm = getEndpoint().getSortTerm();
@@ -478,9 +656,9 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
             }
         } else {
             if (searchTerm != null) {
-                messages = folder.search(searchTerm, retrieveAllMessages());
+                messages = folder.search(searchTerm, 
retrieveAllMessages(count));
             } else {
-                messages = retrieveAllMessages();
+                messages = retrieveAllMessages(count);
             }
             // Now we can sort (emulate email sort but restrict sort terms)
             if (sortTerm != null) {
@@ -539,8 +717,7 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
         return answer;
     }
 
-    private Message[] retrieveAllMessages() throws MessagingException {
-        int total = folder.getMessageCount();
+    private Message[] retrieveAllMessages(int total) throws MessagingException 
{
         List<Message> msgs = new ArrayList<>();
 
         // Note that message * numbers start at 1, not 0
@@ -690,17 +867,24 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
      * @param exchange the exchange
      */
     protected void processCommit(Message mail, Exchange exchange) {
+        String uid = (String) exchange.removeProperty(MAIL_MESSAGE_UID);
+        boolean pop3 = 
getEndpoint().getConfiguration().getProtocol().startsWith("pop3");
         try {
             // ensure folder is open
             if (!folder.isOpen()) {
+                if (!pop3) {
+                    // mailToCommit checked this IMAP mail object against the 
open folder, and neither the poll nor
+                    // doStop can close it meanwhile: its connection dropped. 
In a new open, the message number of the
+                    // mail object can designate another mail, so it is not 
marked
+                    throw new FolderClosedException(
+                            folder, "The folder was closed after the mail was 
checked, so the mail is not marked");
+                }
                 openFolder();
             }
 
-            String uid = (String) exchange.removeProperty(MAIL_MESSAGE_UID);
-
             // If the protocol is POP3, the message needs to be synced with 
the folder via the UID.
             // Otherwise setting the DELETE/SEEN flag won't delete the message.
-            if 
(getEndpoint().getConfiguration().getProtocol().startsWith("pop3")) {
+            if (pop3) {
                 int count = folder.getMessageCount();
                 Message found = null;
                 LOG.trace("Looking for POP3Message with UID {} from folder 
with {} mails", uid, count);
@@ -740,24 +924,19 @@ public class MailConsumer extends 
ScheduledBatchPollingConsumer {
                 mail.setFlag(Flags.Flag.SEEN, true);
                 copyOrMoveMessageIfRequired(config, mail, moveTo, true);
             }
-
-            // need to confirm or remove on commit at last
-            if (getEndpoint().getIdempotentRepository() != null) {
-                if (getEndpoint().isIdempotentRepositoryRemoveOnCommit()) {
-                    getEndpoint().getIdempotentRepository().remove(uid);
-                } else {
-                    getEndpoint().getIdempotentRepository().confirm(uid);
-                }
-            }
-
         } catch (MessageRemovedException e) {
             MessagingException wrapped = new MessagingException(
                     "Message already removed/expunged on server (message state 
could not be updated)", e);
-            getExceptionHandler().handleException(
-                    "Error occurred during committing mail message: " + mail, 
exchange, wrapped);
-        } catch (MessagingException e) {
-            getExceptionHandler().handleException("Error occurred during 
committing mail message: " + mail, exchange, e);
+            handleCommitException(mail, exchange, wrapped);
+        } catch (MessagingException | IllegalStateException e) {
+            // IllegalStateException: the folder or the store is not open any 
more (IMAPFolder checkOpened, IMAPStore
+            // not connected)
+            handleCommitException(mail, exchange, e);
         }
+
+        // need to confirm or remove on commit at last; also when the mail 
could not be marked, so it is not skipped as
+        // a duplicate for good (as mailToCommit does)
+        commitIdempotentKey(uid);
     }
 
     private Exchange createExchange(Message message) {
diff --git 
a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerAsyncCommitStressTest.java
 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerAsyncCommitStressTest.java
new file mode 100644
index 000000000000..3196518aa773
--- /dev/null
+++ 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerAsyncCommitStressTest.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.mail;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import jakarta.mail.Folder;
+import jakarta.mail.Message;
+import jakarta.mail.Store;
+import jakarta.mail.internet.MimeMessage;
+
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mail.Mailbox.MailboxUser;
+import org.apache.camel.component.mail.Mailbox.Protocol;
+import org.apache.camel.support.KeyValueIdempotentRepository;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Many pollEnrich calls on 4 threads: their exchanges complete on the caller 
threads while the poll of the pollEnrich
+ * consumer connects, closes the folder or disconnects. No call hangs, every 
mail is routed once, and every mail is
+ * marked.
+ */
+class MailConsumerAsyncCommitStressTest extends CamelTestSupport {
+    private static final int MAILS = 20;
+    private static final int THREADS = 4;
+    private static final MailboxUser dan = 
Mailbox.getOrCreateUser("MailConsumerAsyncCommitStressTest-dan", "secret");
+    private static final MailboxUser cat = 
Mailbox.getOrCreateUser("MailConsumerAsyncCommitStressTest-cat", "secret");
+    private static final MailboxUser pat = 
Mailbox.getOrCreateUser("MailConsumerAsyncCommitStressTest-pat", "secret");
+
+    @BindToRegistry("repo")
+    private final KeyValueIdempotentRepository repo = new 
KeyValueIdempotentRepository();
+
+    @Override
+    public void setupResources() throws Exception {
+        for (MailboxUser user : new MailboxUser[] { dan, cat, pat }) {
+            Mailbox.clearAll(user);
+            JavaMailSender sender = new DefaultJavaMailSender();
+            Store store = sender.getSession().getStore("imap");
+            store.connect("localhost", Mailbox.getPort(Protocol.imap), 
user.getLogin(), user.getPassword());
+            Folder folder = store.getFolder("INBOX");
+            folder.open(Folder.READ_WRITE);
+            Message[] messages = new Message[MAILS];
+            for (int i = 0; i < MAILS; i++) {
+                messages[i] = new MimeMessage(sender.getSession());
+                messages[i].setSubject("Mail " + i);
+                messages[i].setText("Message " + i);
+            }
+            folder.appendMessages(messages);
+            folder.close(true);
+            store.close();
+        }
+    }
+
+    @Test
+    void imapDisconnectAndDelete() throws Exception {
+        enrichAllMailsConcurrently("direct:dan", "mock:dan");
+        await().atMost(30, TimeUnit.SECONDS).untilAsserted(() -> 
assertEquals(0, dan.getInbox().getMessageCount()));
+    }
+
+    @Test
+    void imapCloseFolderAndSeen() throws Exception {
+        enrichAllMailsConcurrently("direct:cat", "mock:cat");
+        await().atMost(30, TimeUnit.SECONDS).untilAsserted(() -> 
assertEquals(0, cat.getInbox().getNewMessageCount()));
+    }
+
+    @Test
+    void pop3DisconnectAndDelete() throws Exception {
+        enrichAllMailsConcurrently("direct:pat", "mock:pat");
+        await().atMost(60, TimeUnit.SECONDS).untilAsserted(() -> 
assertEquals(0, pat.getInbox().getMessageCount()));
+    }
+
+    private void enrichAllMailsConcurrently(String from, String to) throws 
Exception {
+        ExecutorService pool = Executors.newFixedThreadPool(THREADS);
+        try {
+            List<Future<?>> calls = new ArrayList<>();
+            for (int t = 0; t < THREADS; t++) {
+                calls.add(pool.submit(() -> {
+                    for (int i = 0; i < MAILS / THREADS; i++) {
+                        template.sendBody(from, "");
+                    }
+                }));
+            }
+            for (Future<?> call : calls) {
+                // a TimeoutException fails the test: a pollEnrich call hangs
+                call.get(90, TimeUnit.SECONDS);
+            }
+        } finally {
+            pool.shutdownNow();
+        }
+        Set<String> bodies = new HashSet<>();
+        for (Exchange exchange : getMockEndpoint(to).getExchanges()) {
+            String body = exchange.getIn().getBody(String.class);
+            if (body != null && !body.isEmpty()) {
+                assertTrue(bodies.add(body.trim()), "mail routed twice: " + 
body);
+            }
+        }
+        assertEquals(MAILS, bodies.size(), "every mail is routed once");
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            public void configure() {
+                String options = 
"&idempotentRepository=#repo&initialDelay=0&delay=20";
+                from("direct:dan").pollEnrich(dan.uriPrefix(Protocol.imap) + 
"&disconnect=true&delete=true" + options, 20000)
+                        .to("mock:dan");
+                from("direct:cat").pollEnrich(cat.uriPrefix(Protocol.imap) + 
"&closeFolder=true" + options, 20000)
+                        .to("mock:cat");
+                from("direct:pat").pollEnrich(pat.uriPrefix(Protocol.pop3) + 
"&disconnect=true&delete=true" + options, 20000)
+                        .to("mock:pat");
+            }
+        };
+    }
+}
diff --git 
a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitAfterDisconnectTest.java
 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitAfterDisconnectTest.java
new file mode 100644
index 000000000000..0a82070bff8a
--- /dev/null
+++ 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitAfterDisconnectTest.java
@@ -0,0 +1,165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.mail;
+
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.TimeUnit;
+
+import jakarta.mail.Folder;
+import jakarta.mail.Message;
+import jakarta.mail.Store;
+import jakarta.mail.internet.MimeMessage;
+
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mail.Mailbox.MailboxUser;
+import org.apache.camel.component.mail.Mailbox.Protocol;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.support.KeyValueIdempotentRepository;
+import org.apache.camel.support.UnitOfWorkHelper;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * With pollEnrich or a ConsumerTemplate, the exchange of a mail completes 
after the poll that retrieved it. With
+ * disconnect=true that poll has disconnected (the consumer has no folder any 
more) when the mail is marked: the mail
+ * must still be marked (the consumer connects again), and its idempotent key 
settled.
+ */
+class MailConsumerCommitAfterDisconnectTest extends CamelTestSupport {
+    private static final MailboxUser ann = 
Mailbox.getOrCreateUser("MailConsumerCommitAfterDisconnectTest-ann", "secret");
+
+    @BindToRegistry("repo")
+    private final KeyValueIdempotentRepository repo = new 
KeyValueIdempotentRepository();
+
+    private final Queue<Exchange> queued = new ConcurrentLinkedQueue<>();
+
+    @Override
+    public void setupResources() throws Exception {
+        Mailbox.clearAll(ann);
+        JavaMailSender sender = new DefaultJavaMailSender();
+        Store store = sender.getSession().getStore("imap");
+        store.connect("localhost", Mailbox.getPort(Protocol.imap), 
ann.getLogin(), ann.getPassword());
+        Folder folder = store.getFolder("INBOX");
+        folder.open(Folder.READ_WRITE);
+        Message message = new MimeMessage(sender.getSession());
+        message.setSubject("Mail 0");
+        message.setText("Message 0");
+        folder.appendMessages(new Message[] { message });
+        folder.close(true);
+        store.close();
+    }
+
+    @Test
+    void 
mailIsMarkedSeenWhenItsExchangeCompletesAfterTheConsumerDisconnected() throws 
Exception {
+        MailConsumer consumer = createConsumer(ann.uriPrefix(Protocol.imap) + 
"&disconnect=true&idempotentRepository=#repo");
+        try {
+            assertEquals(1, consumer.poll());
+            Exchange exchange = queued.poll();
+            assertNotNull(exchange);
+            String key = exchange.getProperty(MailConsumer.MAIL_MESSAGE_UID, 
String.class);
+            assertTrue(repo.contains(key));
+
+            // the poll disconnected; the exchange completes now 
(ConsumerTemplate.doneUoW, or the end of pollEnrich)
+            complete(exchange);
+
+            assertEquals(0, ann.getInbox().getNewMessageCount(), "the mail of 
the completed exchange is marked SEEN");
+            assertFalse(repo.contains(key), "the key of the mail is removed on 
commit");
+            // the next poll does not route the mail again
+            assertEquals(0, consumer.poll());
+        } finally {
+            consumer.stop();
+        }
+    }
+
+    @Test
+    void mailIsDeletedWhenItsExchangeCompletesAfterTheConsumerDisconnected() 
throws Exception {
+        MailConsumer consumer = createConsumer(ann.uriPrefix(Protocol.imap) + 
"&disconnect=true&delete=true");
+        try {
+            assertEquals(1, consumer.poll());
+            complete(queued.poll());
+
+            // flagged DELETED, and expunged when the consumer disconnected 
again
+            assertEquals(0, ann.getInbox().getMessageCount(), "the mail of the 
completed exchange is deleted");
+        } finally {
+            consumer.stop();
+        }
+    }
+
+    @Test
+    void 
pop3MailIsDeletedWhenItsExchangeCompletesAfterTheConsumerDisconnected() throws 
Exception {
+        MailConsumer consumer = createConsumer(ann.uriPrefix(Protocol.pop3) + 
"&disconnect=true&delete=true");
+        try {
+            assertEquals(1, consumer.poll());
+            complete(queued.poll());
+
+            assertEquals(0, ann.getInbox().getMessageCount(), "the mail of the 
completed exchange is deleted");
+        } finally {
+            consumer.stop();
+        }
+    }
+
+    @Test
+    void pollEnrichWithDisconnectDeletesTheMail() throws Exception {
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.expectedBodiesReceived("Message 0");
+
+        template.sendBody("direct:start", "");
+
+        MockEndpoint.assertIsSatisfied(context);
+        // the exchange completed after the poll of the pollEnrich consumer 
disconnected
+        await().atMost(10, TimeUnit.SECONDS)
+                .untilAsserted(() -> assertEquals(0, 
ann.getInbox().getMessageCount(), "the enriched mail is deleted"));
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            public void configure() {
+                from("direct:start")
+                        .pollEnrich(ann.uriPrefix(Protocol.imap) + 
"&disconnect=true&delete=true&initialDelay=10&delay=100",
+                                5000)
+                        .to("mock:result");
+            }
+        };
+    }
+
+    /**
+     * A consumer whose processor only queues the exchange, as the polling 
consumer of pollEnrich and ConsumerTemplate
+     * does: the exchange completes later, on the test thread.
+     */
+    private MailConsumer createConsumer(String uri) throws Exception {
+        MailEndpoint endpoint = context.getEndpoint(uri, MailEndpoint.class);
+        JavaMailSender sender = 
endpoint.getConfiguration().createJavaMailSender(context);
+        endpoint.getConfiguration().configureJavaMailSender(context, sender);
+        MailConsumer consumer = new MailConsumer(endpoint, queued::add, 
sender);
+        consumer.setStartScheduler(false);
+        consumer.start();
+        return consumer;
+    }
+
+    private static void complete(Exchange exchange) {
+        UnitOfWorkHelper.doneSynchronizations(exchange, 
exchange.getExchangeExtension().handoverCompletions());
+    }
+}
diff --git 
a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitAfterStopTest.java
 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitAfterStopTest.java
new file mode 100644
index 000000000000..ec0cb58cf9fb
--- /dev/null
+++ 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitAfterStopTest.java
@@ -0,0 +1,251 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.mail;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import jakarta.mail.Folder;
+import jakarta.mail.Message;
+import jakarta.mail.Store;
+import jakarta.mail.internet.MimeMessage;
+
+import javax.net.SocketFactory;
+
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.Exchange;
+import org.apache.camel.component.mail.Mailbox.MailboxUser;
+import org.apache.camel.component.mail.Mailbox.Protocol;
+import org.apache.camel.support.KeyValueIdempotentRepository;
+import org.apache.camel.support.UnitOfWorkHelper;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * With pollEnrich or a ConsumerTemplate, the exchange of a mail can complete 
after its consumer was stopped. The stop
+ * closed the folder and the store; the completion must not open the folder or 
connect again (IMAPStore would log in
+ * with the credentials the closed store kept, and nobody would close that 
connection). The mail is not marked and its
+ * idempotent key is settled as on commit. A poll that is stopped after it 
connected, or that comes after the stop, does
+ * not connect again either. The connections are counted by the socket factory 
of the JavaMail session.
+ */
+class MailConsumerCommitAfterStopTest extends CamelTestSupport {
+    private static final MailboxUser bob = 
Mailbox.getOrCreateUser("MailConsumerCommitAfterStopTest-bob", "secret");
+
+    @BindToRegistry("repo")
+    private final KeyValueIdempotentRepository repo = new 
KeyValueIdempotentRepository();
+
+    private final Queue<Exchange> queued = new ConcurrentLinkedQueue<>();
+    private final CountingSocketFactory sockets = new CountingSocketFactory();
+
+    @Override
+    public void setupResources() throws Exception {
+        Mailbox.clearAll(bob);
+        JavaMailSender sender = new DefaultJavaMailSender();
+        Store store = sender.getSession().getStore("imap");
+        store.connect("localhost", Mailbox.getPort(Protocol.imap), 
bob.getLogin(), bob.getPassword());
+        Folder folder = store.getFolder("INBOX");
+        folder.open(Folder.READ_WRITE);
+        Message message = new MimeMessage(sender.getSession());
+        message.setSubject("Mail 0");
+        message.setText("Message 0");
+        folder.appendMessages(new Message[] { message });
+        folder.close(true);
+        store.close();
+    }
+
+    @Test
+    void imapCommitAfterStopDoesNotConnectAgain() throws Exception {
+        commitAfterStop(bob.uriPrefix(Protocol.imap) + 
"&idempotentRepository=#repo", false);
+        assertEquals(1, bob.getInbox().getNewMessageCount(), "the mail is not 
marked SEEN");
+    }
+
+    @Test
+    void imapCommitAfterStopWithCloseFolderDoesNotConnectAgain() throws 
Exception {
+        commitAfterStop(bob.uriPrefix(Protocol.imap) + 
"&closeFolder=true&idempotentRepository=#repo", false);
+        assertEquals(1, bob.getInbox().getNewMessageCount(), "the mail is not 
marked SEEN");
+    }
+
+    @Test
+    void imapCommitAfterStopConfirmsKeyWhenNotRemovedOnCommit() throws 
Exception {
+        commitAfterStop(bob.uriPrefix(Protocol.imap) + 
"&idempotentRepository=#repo&idempotentRepositoryRemoveOnCommit=false",
+                true);
+        assertEquals(1, bob.getInbox().getNewMessageCount(), "the mail is not 
marked SEEN");
+    }
+
+    @Test
+    void pop3CommitAfterStopDoesNotConnectAgain() throws Exception {
+        commitAfterStop(bob.uriPrefix(Protocol.pop3) + 
"&delete=true&idempotentRepository=#repo", false);
+        assertEquals(1, bob.getInbox().getMessageCount(), "the mail is not 
deleted");
+    }
+
+    @Test
+    void pollAfterStopDoesNotConnectAgain() throws Exception {
+        MailConsumer consumer = createConsumer(bob.uriPrefix(Protocol.imap) + 
"&idempotentRepository=#repo", false);
+        consumer.stop();
+
+        // a poll that was already running when the consumer stopped, and had 
not connected yet
+        assertEquals(0, consumer.poll(), "a stopped consumer does not poll the 
mailbox");
+        assertEquals(0, sockets.created(), "the stopped consumer did not 
connect");
+        assertTrue(queued.isEmpty());
+        assertEquals(1, bob.getInbox().getNewMessageCount());
+    }
+
+    @Test
+    void pollStoppedAfterItConnectedDoesNotConnectAgain() throws Exception {
+        pollStoppedAfterItConnected(bob.uriPrefix(Protocol.imap) + 
"&idempotentRepository=#repo");
+    }
+
+    @Test
+    void pollStoppedAfterItConnectedWithDisconnectDoesNotConnectAgain() throws 
Exception {
+        pollStoppedAfterItConnected(bob.uriPrefix(Protocol.imap) + 
"&disconnect=true&idempotentRepository=#repo");
+    }
+
+    private void pollStoppedAfterItConnected(String uri) throws Exception {
+        // the consumer is stopped right after the poll connected, opened the 
folder and released the lock
+        // (forceConsumerAsReady runs there), as a route stop or a forced 
shutdown can during a poll
+        MailConsumer consumer = createConsumer(uri, true);
+
+        assertEquals(0, consumer.poll(), "the poll that was stopped does not 
route a mail");
+        assertTrue(sockets.atStop() > 0, "the poll connected before the stop");
+        // on a closed IMAP folder, getMessageCount asks the server through 
the closed store, which logs in again
+        assertEquals(sockets.atStop(), sockets.created(), "the stopped 
consumer did not connect again");
+        assertTrue(queued.isEmpty());
+        assertEquals(1, bob.getInbox().getNewMessageCount(), "the mail is not 
marked SEEN");
+    }
+
+    private void commitAfterStop(String uri, boolean keyKept) throws Exception 
{
+        MailConsumer consumer = createConsumer(uri, false);
+        assertEquals(1, consumer.poll());
+        Exchange exchange = queued.poll();
+        assertNotNull(exchange);
+        String key = exchange.getProperty(MailConsumer.MAIL_MESSAGE_UID, 
String.class);
+        assertTrue(repo.contains(key));
+        Folder folder = ((MailMessage) 
exchange.getIn()).getOriginalMessage().getFolder();
+
+        consumer.stop();
+        assertFalse(folder.isOpen());
+        assertFalse(folder.getStore().isConnected());
+        int connections = sockets.created();
+
+        // the exchange completes now (ConsumerTemplate.doneUoW, or the end of 
pollEnrich)
+        UnitOfWorkHelper.doneSynchronizations(exchange, 
exchange.getExchangeExtension().handoverCompletions());
+
+        boolean open = folder.isOpen();
+        try {
+            assertFalse(open, "the stopped consumer did not open the folder 
again");
+            assertEquals(connections, sockets.created(), "the stopped consumer 
did not connect again");
+            assertEquals(keyKept, repo.contains(key),
+                    "the key of the mail that is not marked is settled as on 
commit (removed, or confirmed)");
+        } finally {
+            if (open) {
+                folder.close(false);
+            }
+        }
+    }
+
+    /**
+     * A consumer whose processor only queues the exchange, as the polling 
consumer of pollEnrich and ConsumerTemplate
+     * does: the exchange completes later, on the test thread. Its store opens 
its connections with the counting socket
+     * factory. With stopWhenReady, the consumer stops itself once its first 
poll connected and opened the folder.
+     */
+    private MailConsumer createConsumer(String uri, boolean stopWhenReady) 
throws Exception {
+        MailEndpoint endpoint = context.getEndpoint(uri, MailEndpoint.class);
+        JavaMailSender sender = 
endpoint.getConfiguration().createJavaMailSender(context);
+        endpoint.getConfiguration().configureJavaMailSender(context, sender);
+        // JavaMail creates the sockets of the IMAP and POP3 stores with this 
factory (an instance, so put, not setProperty)
+        sender.getSession().getProperties().put("mail." + 
endpoint.getConfiguration().getProtocol() + ".socketFactory",
+                sockets);
+        MailConsumer consumer;
+        if (stopWhenReady) {
+            consumer = new MailConsumer(endpoint, queued::add, sender) {
+                @Override
+                protected void forceConsumerAsReady() {
+                    super.forceConsumerAsReady();
+                    if (sockets.atStop() < 0) {
+                        stop();
+                        sockets.stopped();
+                    }
+                }
+            };
+        } else {
+            consumer = new MailConsumer(endpoint, queued::add, sender);
+        }
+        consumer.setStartScheduler(false);
+        consumer.start();
+        return consumer;
+    }
+
+    /**
+     * Counts the sockets JavaMail creates, one per connection to the mail 
server.
+     */
+    private static final class CountingSocketFactory extends SocketFactory {
+        private final AtomicInteger created = new AtomicInteger();
+        private volatile int atStop = -1;
+
+        int created() {
+            return created.get();
+        }
+
+        int atStop() {
+            return atStop;
+        }
+
+        void stopped() {
+            atStop = created.get();
+        }
+
+        @Override
+        public Socket createSocket() {
+            created.incrementAndGet();
+            return new Socket();
+        }
+
+        @Override
+        public Socket createSocket(String host, int port) throws IOException {
+            created.incrementAndGet();
+            return new Socket(host, port);
+        }
+
+        @Override
+        public Socket createSocket(String host, int port, InetAddress 
localHost, int localPort) throws IOException {
+            created.incrementAndGet();
+            return new Socket(host, port, localHost, localPort);
+        }
+
+        @Override
+        public Socket createSocket(InetAddress host, int port) throws 
IOException {
+            created.incrementAndGet();
+            return new Socket(host, port);
+        }
+
+        @Override
+        public Socket createSocket(InetAddress address, int port, InetAddress 
localAddress, int localPort)
+                throws IOException {
+            created.incrementAndGet();
+            return new Socket(address, port, localAddress, localPort);
+        }
+    }
+}
diff --git 
a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitErrorWithoutLockTest.java
 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitErrorWithoutLockTest.java
new file mode 100644
index 000000000000..4ffad33a6472
--- /dev/null
+++ 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitErrorWithoutLockTest.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.mail;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReentrantLock;
+
+import jakarta.mail.Flags;
+import jakarta.mail.Folder;
+import jakarta.mail.Message;
+import jakarta.mail.MessageRemovedException;
+import jakarta.mail.MessagingException;
+import jakarta.mail.Session;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExtendedCamelContext;
+import org.apache.camel.Processor;
+import org.apache.camel.component.mail.Mailbox.Protocol;
+import org.apache.camel.spi.ExceptionHandler;
+import org.apache.camel.spi.ExchangeFactory;
+import org.apache.camel.spi.IdempotentRepository;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * The completion of an exchange checks and marks its mail while holding the 
folder lock of the consumer, but passes an
+ * error of the mark to the exception handler only after it released the lock: 
with bridgeErrorHandler=true the handler
+ * routes the error through the error handler of the route, and the next poll 
and the stop of the consumer must not wait
+ * for that.
+ */
+class MailConsumerCommitErrorWithoutLockTest {
+
+    private static final String KEY = "mail-key";
+
+    private final IdempotentRepository repository = 
mock(IdempotentRepository.class);
+    private final Folder folder = mock(Folder.class);
+    private final Message mail = mock(Message.class);
+    private final Exchange exchange = mock(Exchange.class);
+    // whether the folder lock was held while the exception handler ran, one 
entry per call
+    private final List<Boolean> lockedInHandler = new ArrayList<>();
+    private MailConsumer consumer;
+    private ReentrantLock folderLock;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        JavaMailSender sender = mock(JavaMailSender.class);
+        CamelContext camelContext = mock(CamelContext.class);
+        ExtendedCamelContext ecc = mock(ExtendedCamelContext.class);
+        ExchangeFactory ef = mock(ExchangeFactory.class);
+        
when(sender.getSession()).thenReturn(Session.getInstance(Mailbox.getSessionProperties(Protocol.imap)));
+        when(camelContext.getCamelContextExtension()).thenReturn(ecc);
+        when(ecc.getExchangeFactory()).thenReturn(ef);
+        when(ef.newExchangeFactory(any())).thenReturn(ef);
+
+        MailEndpoint endpoint = new MailEndpoint();
+        endpoint.setCamelContext(camelContext);
+        MailConfiguration config = new MailConfiguration();
+        config.configureProtocol(Protocol.imap.name());
+        endpoint.setConfiguration(config);
+        endpoint.setIdempotentRepository(repository);
+
+        org.apache.camel.Message in = mock(org.apache.camel.Message.class);
+        when(exchange.getIn()).thenReturn(in);
+        when(in.getHeader(MailConstants.MAIL_DELETE, false, 
boolean.class)).thenReturn(false);
+        
when(exchange.removeProperty(MailConsumer.MAIL_MESSAGE_UID)).thenReturn(KEY);
+        when(folder.getFullName()).thenReturn("INBOX");
+
+        // a started consumer (commit does not mark the mail of a stopped one)
+        consumer = new MailConsumer(endpoint, mock(Processor.class), sender) {
+            @Override
+            public boolean isRunAllowed() {
+                return true;
+            }
+        };
+        Field folderField = MailConsumer.class.getDeclaredField("folder");
+        folderField.setAccessible(true);
+        folderField.set(consumer, folder);
+        Field lockField = MailConsumer.class.getDeclaredField("folderLock");
+        lockField.setAccessible(true);
+        folderLock = (ReentrantLock) lockField.get(consumer);
+
+        ExceptionHandler exceptionHandler = mock(ExceptionHandler.class);
+        doAnswer(invocation -> lockedInHandler.add(folderLock.isLocked()))
+                .when(exceptionHandler).handleException(any(), any(), any());
+        consumer.setExceptionHandler(exceptionHandler);
+    }
+
+    @Test
+    void markThatFailsIsReportedWithoutTheLock() throws Exception {
+        when(folder.isOpen()).thenReturn(true);
+        doThrow(new 
MessageRemovedException("expunged")).when(mail).setFlag(any(Flags.Flag.class), 
anyBoolean());
+
+        consumer.commit(mail, 5L, 7L, 0, exchange);
+
+        assertEquals(1, lockedInHandler.size(), "the failed mark is reported 
once");
+        assertFalse(lockedInHandler.get(0), "the exception handler ran while 
the folder lock was held");
+        verify(repository).remove(KEY);
+    }
+
+    @Test
+    void folderThatCannotBeOpenedAgainIsReportedWithoutTheLock() throws 
Exception {
+        // the folder was opened again since the poll of the mail, and it 
cannot be opened now
+        Field opensField = MailConsumer.class.getDeclaredField("folderOpens");
+        opensField.setAccessible(true);
+        ((AtomicInteger) opensField.get(consumer)).set(1);
+        when(folder.isOpen()).thenReturn(false);
+        doThrow(new MessagingException("connection 
refused")).when(folder).open(Folder.READ_WRITE);
+
+        consumer.commit(mail, 5L, 7L, 0, exchange);
+
+        assertEquals(1, lockedInHandler.size(), "the failed open is reported 
once");
+        assertFalse(lockedInHandler.get(0), "the exception handler ran while 
the folder lock was held");
+        verify(repository).remove(KEY);
+    }
+
+    @Test
+    void markThatFailsIsReportedAlsoWhenTheRepositoryThrows() throws Exception 
{
+        when(folder.isOpen()).thenReturn(true);
+        doThrow(new 
MessageRemovedException("expunged")).when(mail).setFlag(any(Flags.Flag.class), 
anyBoolean());
+        IllegalStateException down = new IllegalStateException("repository 
down");
+        doThrow(down).when(repository).remove(KEY);
+
+        IllegalStateException thrown
+                = assertThrows(IllegalStateException.class, () -> 
consumer.commit(mail, 5L, 7L, 0, exchange));
+
+        assertSame(down, thrown, "the exception of the repository still 
propagates");
+        assertEquals(1, lockedInHandler.size(), "the failed mark is reported 
although the repository threw");
+        assertFalse(lockedInHandler.get(0), "the exception handler ran while 
the folder lock was held");
+        assertFalse(folderLock.isLocked(), "the folder lock is released");
+    }
+}
diff --git 
a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitFailedKeyTest.java
 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitFailedKeyTest.java
new file mode 100644
index 000000000000..2a56691b6abf
--- /dev/null
+++ 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitFailedKeyTest.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.mail;
+
+import java.lang.reflect.Field;
+
+import jakarta.mail.Flags;
+import jakarta.mail.Folder;
+import jakarta.mail.FolderClosedException;
+import jakarta.mail.Message;
+import jakarta.mail.MessageRemovedException;
+import jakarta.mail.MessagingException;
+import jakarta.mail.Session;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExtendedCamelContext;
+import org.apache.camel.Processor;
+import org.apache.camel.component.mail.Mailbox.Protocol;
+import org.apache.camel.spi.ExceptionHandler;
+import org.apache.camel.spi.ExchangeFactory;
+import org.apache.camel.spi.IdempotentRepository;
+import org.junit.jupiter.api.Test;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * When the mail of a completed exchange cannot be marked (the mail was 
expunged meanwhile, or the connection of the
+ * folder dropped, as IMAPMessage reports it), the error is reported and the 
idempotent key of the mail is settled as on
+ * commit (removed by default, confirmed with 
idempotentRepositoryRemoveOnCommit=false), so the mail is not skipped as a
+ * duplicate until the repository forgets the key.
+ */
+class MailConsumerCommitFailedKeyTest {
+
+    private static final String KEY = "mail-key";
+
+    private final IdempotentRepository repository = 
mock(IdempotentRepository.class);
+    private final ExceptionHandler exceptionHandler = 
mock(ExceptionHandler.class);
+
+    @Test
+    void keyIsRemovedWhenTheMailWasExpunged() throws Exception {
+        commitFailingWith(new MessageRemovedException("expunged"), true);
+
+        verify(exceptionHandler).handleException(anyString(), 
any(Exchange.class), any(MessagingException.class));
+        verify(repository).remove(KEY);
+    }
+
+    @Test
+    void keyIsConfirmedWhenTheConnectionDroppedAndKeysAreKept() throws 
Exception {
+        commitFailingWith(new FolderClosedException(mock(Folder.class), 
"connection dropped"), false);
+
+        verify(exceptionHandler).handleException(anyString(), 
any(Exchange.class), any(FolderClosedException.class));
+        verify(repository).confirm(KEY);
+        verify(repository, never()).remove(KEY);
+    }
+
+    private void commitFailingWith(MessagingException failure, boolean 
removeOnCommit) throws Exception {
+        JavaMailSender sender = mock(JavaMailSender.class);
+        CamelContext camelContext = mock(CamelContext.class);
+        ExtendedCamelContext ecc = mock(ExtendedCamelContext.class);
+        ExchangeFactory ef = mock(ExchangeFactory.class);
+        
when(sender.getSession()).thenReturn(Session.getInstance(Mailbox.getSessionProperties(Protocol.imap)));
+        when(camelContext.getCamelContextExtension()).thenReturn(ecc);
+        when(ecc.getExchangeFactory()).thenReturn(ef);
+        when(ef.newExchangeFactory(any())).thenReturn(ef);
+
+        MailEndpoint endpoint = new MailEndpoint();
+        endpoint.setCamelContext(camelContext);
+        MailConfiguration config = new MailConfiguration();
+        config.configureProtocol(Protocol.imap.name());
+        endpoint.setConfiguration(config);
+        endpoint.setIdempotentRepository(repository);
+        endpoint.setIdempotentRepositoryRemoveOnCommit(removeOnCommit);
+
+        Folder folder = mock(Folder.class);
+        when(folder.isOpen()).thenReturn(true);
+        Message mail = mock(Message.class);
+        doThrow(failure).when(mail).setFlag(any(Flags.Flag.class), 
anyBoolean());
+        Exchange exchange = mock(Exchange.class);
+        org.apache.camel.Message in = mock(org.apache.camel.Message.class);
+        when(exchange.getIn()).thenReturn(in);
+        when(in.getHeader(MailConstants.MAIL_DELETE, false, 
boolean.class)).thenReturn(false);
+        
when(exchange.removeProperty(MailConsumer.MAIL_MESSAGE_UID)).thenReturn(KEY);
+
+        MailConsumer consumer = new MailConsumer(endpoint, 
mock(Processor.class), sender);
+        consumer.setExceptionHandler(exceptionHandler);
+        Field folderField = MailConsumer.class.getDeclaredField("folder");
+        folderField.setAccessible(true);
+        folderField.set(consumer, folder);
+
+        consumer.processCommit(mail, exchange);
+    }
+}
diff --git 
a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitWhileFolderClosesTest.java
 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitWhileFolderClosesTest.java
new file mode 100644
index 000000000000..71860632f67a
--- /dev/null
+++ 
b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailConsumerCommitWhileFolderClosesTest.java
@@ -0,0 +1,286 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.mail;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.LockSupport;
+
+import jakarta.mail.Flags;
+import jakarta.mail.Folder;
+import jakarta.mail.Message;
+import jakarta.mail.MessagingException;
+import jakarta.mail.Store;
+import jakarta.mail.internet.MimeMessage;
+
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.component.mail.Mailbox.MailboxUser;
+import org.apache.camel.component.mail.Mailbox.Protocol;
+import org.apache.camel.support.KeyValueIdempotentRepository;
+import org.apache.camel.support.UnitOfWorkHelper;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The mail of an exchange is checked against the open of the folder in which 
it was retrieved, then marked. The folder
+ * must not be closed or opened again between the two: after an expunge, the 
message number of the mail object
+ * designates another mail in a new open of the folder. The poll closes the 
folder (closeFolder=true) or disconnects
+ * (disconnect=true) at its end, while an exchange that is completed on 
another thread (pollEnrich, ConsumerTemplate)
+ * marks its mail; the connection of the folder can also drop. The mail server 
is the in-JVM GreenMail IMAP server.
+ */
+class MailConsumerCommitWhileFolderClosesTest extends CamelTestSupport {
+    private static final MailboxUser kai = 
Mailbox.getOrCreateUser("MailConsumerCommitWhileFolderClosesTest-kai", 
"secret");
+
+    @BindToRegistry("repo")
+    private final KeyValueIdempotentRepository repo = new 
KeyValueIdempotentRepository();
+
+    private final Map<String, Exchange> queued = new ConcurrentHashMap<>();
+    private final ExecutorService threads = Executors.newFixedThreadPool(2);
+    private final AtomicReference<Future<?>> completion = new 
AtomicReference<>();
+    private final AtomicReference<String> keyOfMail1 = new AtomicReference<>();
+
+    @Override
+    public void setupResources() throws Exception {
+        Mailbox.clearAll(kai);
+        JavaMailSender sender = new DefaultJavaMailSender();
+        Message[] messages = new Message[3];
+        for (int i = 0; i < 3; i++) {
+            messages[i] = new MimeMessage(sender.getSession());
+            messages[i].setSubject("Mail " + i);
+            messages[i].setText("Message " + i);
+        }
+        Store store = openStore();
+        Folder folder = store.getFolder("INBOX");
+        folder.open(Folder.READ_WRITE);
+        folder.appendMessages(messages);
+        folder.close(true);
+        store.close();
+    }
+
+    @AfterEach
+    void stopThreads() {
+        threads.shutdownNow();
+    }
+
+    /**
+     * The connection of the folder drops after the mail of "Mail 1" was 
checked, and another client expunges "Mail 0":
+     * the mail object of "Mail 1" now has the message number of "Mail 2" in a 
new open. No mail is marked, the key of
+     * "Mail 1" is removed, and the next poll routes "Mail 1" again.
+     */
+    @Test
+    void mailIsNotMarkedWhenTheConnectionDropsAfterItWasChecked() throws 
Exception {
+        MailConsumer consumer = new 
MailConsumer(endpoint("&idempotentRepository=#repo"), handOff(), sender()) {
+            @Override
+            protected void processCommit(Message mail, Exchange exchange) {
+                if (exchange == queued.get("Mail 1")) {
+                    try {
+                        // the connection of the folder drops (the consumer's 
folder is closed)
+                        mail.getFolder().close(false);
+                        removeByAnotherClient("Mail 0");
+                    } catch (Exception e) {
+                        throw new IllegalStateException(e);
+                    }
+                }
+                super.processCommit(mail, exchange);
+            }
+        };
+        start(consumer);
+        try {
+            assertEquals(2, consumer.poll());
+            Exchange exchange = queued.get("Mail 1");
+            String key = exchange.getProperty(MailConsumer.MAIL_MESSAGE_UID, 
String.class);
+            complete(exchange);
+
+            assertFalse(isSeen("Mail 2"), "a mail that was never retrieved is 
not marked");
+            assertFalse(isSeen("Mail 1"), "the mail is not marked by its stale 
message number");
+            assertFalse(repo.contains(key), "the key of the mail that is not 
marked is removed");
+            // the next poll consumes "Mail 1" again (and "Mail 2")
+            queued.clear();
+            assertEquals(2, consumer.poll());
+            assertTrue(queued.containsKey("Mail 1"), "the mail is routed 
again");
+        } finally {
+            consumer.stop();
+        }
+    }
+
+    /**
+     * closeFolder=true: the exchange of "Mail 1" completes on another thread 
while the poll ends. After its mail was
+     * checked against the open folder, the poll would close the folder and 
another client expunges "Mail 0": marking
+     * the mail object of "Mail 1" in a new open marks "Mail 2". The poll must 
wait to close the folder until the mail
+     * is marked.
+     */
+    @Test
+    void pollClosesTheFolderAfterACompletingMailIsMarked() throws Exception {
+        CountDownLatch expunged = new CountDownLatch(1);
+        Future<Integer> poll = runPollWhileMail1Completes("&closeFolder=true", 
expunged);
+        assertEquals(2, poll.get(20, TimeUnit.SECONDS));
+        // another client expunges "Mail 0" once the poll closed the folder
+        removeByAnotherClient("Mail 0");
+        expunged.countDown();
+        completion.get().get(20, TimeUnit.SECONDS);
+
+        assertTrue(isSeen("Mail 1"), "the mail of the completed exchange is 
marked SEEN");
+        assertFalse(isSeen("Mail 2"), "a mail that was never retrieved is not 
marked");
+    }
+
+    /**
+     * disconnect=true: the poll would disconnect (the consumer has no folder 
any more) after the mail of "Mail 1" was
+     * checked. The poll must wait to disconnect until the mail is marked.
+     */
+    @Test
+    void pollDisconnectsAfterACompletingMailIsMarked() throws Exception {
+        Future<Integer> poll = 
runPollWhileMail1Completes("&disconnect=true&idempotentRepository=#repo", null);
+        assertEquals(2, poll.get(20, TimeUnit.SECONDS));
+        completion.get().get(20, TimeUnit.SECONDS);
+        String key = keyOfMail1.get();
+
+        assertTrue(isSeen("Mail 1"), "the mail of the completed exchange is 
marked SEEN");
+        assertFalse(repo.contains(key), "the key of the mail is removed on 
commit");
+    }
+
+    /**
+     * Polls "Mail 0" and "Mail 1" on one thread; the exchange of "Mail 1" 
completes on another thread. Its mail is
+     * checked, then the commit waits until the poll ended or waits to end (on 
the poll thread, once "Mail 1" was handed
+     * off, nothing else parks). When the poll ended, the commit also waits 
for the given latch.
+     */
+    private Future<Integer> runPollWhileMail1Completes(String options, 
CountDownLatch beforeMark) throws Exception {
+        CountDownLatch mail1HandedOff = new CountDownLatch(1);
+        CountDownLatch mail1Checked = new CountDownLatch(1);
+        AtomicBoolean handOffReturned = new AtomicBoolean();
+        AtomicReference<Thread> pollThread = new AtomicReference<>();
+        AtomicReference<Future<Integer>> pollRef = new AtomicReference<>();
+        Processor handOff = exchange -> {
+            String subject = exchange.getIn().getHeader("Subject", 
String.class);
+            queued.put(subject, exchange);
+            if ("Mail 1".equals(subject)) {
+                
keyOfMail1.set(exchange.getProperty(MailConsumer.MAIL_MESSAGE_UID, 
String.class));
+                pollThread.set(Thread.currentThread());
+                mail1HandedOff.countDown();
+                // the poll goes on once the other thread checked the mail
+                assertTrue(mail1Checked.await(20, TimeUnit.SECONDS));
+                handOffReturned.set(true);
+            }
+        };
+        MailConsumer consumer = new MailConsumer(endpoint(options), handOff, 
sender()) {
+            @Override
+            protected void processCommit(Message mail, Exchange exchange) {
+                if (exchange == queued.get("Mail 1")) {
+                    mail1Checked.countDown();
+                    await().atMost(20, TimeUnit.SECONDS).until(() -> 
pollRef.get().isDone()
+                            || handOffReturned.get() && 
isParked(pollThread.get()));
+                    if (pollRef.get().isDone() && beforeMark != null) {
+                        try {
+                            assertTrue(beforeMark.await(20, TimeUnit.SECONDS));
+                        } catch (InterruptedException e) {
+                            Thread.currentThread().interrupt();
+                            throw new IllegalStateException(e);
+                        }
+                    }
+                }
+                super.processCommit(mail, exchange);
+            }
+        };
+        start(consumer);
+        context.addService(consumer);
+        pollRef.set(threads.submit(consumer::poll));
+        completion.set(threads.submit(() -> {
+            assertTrue(mail1HandedOff.await(20, TimeUnit.SECONDS));
+            // the exchange of "Mail 1" completed successfully: its 
synchronizations run (as ConsumerTemplate.doneUoW)
+            complete(queued.get("Mail 1"));
+            return null;
+        }));
+        return pollRef.get();
+    }
+
+    private static boolean isParked(Thread thread) {
+        return thread.getState() == Thread.State.WAITING && 
LockSupport.getBlocker(thread) != null;
+    }
+
+    private MailEndpoint endpoint(String options) {
+        return context.getEndpoint(kai.uriPrefix(Protocol.imap) + 
"&maxMessagesPerPoll=2" + options, MailEndpoint.class);
+    }
+
+    private Processor handOff() {
+        return exchange -> queued.put(exchange.getIn().getHeader("Subject", 
String.class), exchange);
+    }
+
+    private JavaMailSender sender() {
+        MailEndpoint endpoint = endpoint("");
+        JavaMailSender sender = 
endpoint.getConfiguration().createJavaMailSender(context);
+        endpoint.getConfiguration().configureJavaMailSender(context, sender);
+        return sender;
+    }
+
+    private static void start(MailConsumer consumer) {
+        consumer.setMaxMessagesPerPoll(2);
+        consumer.setStartScheduler(false);
+        consumer.start();
+    }
+
+    private static void complete(Exchange exchange) {
+        UnitOfWorkHelper.doneSynchronizations(exchange, 
exchange.getExchangeExtension().handoverCompletions());
+    }
+
+    private static void removeByAnotherClient(String subject) throws 
MessagingException {
+        Store store = openStore();
+        Folder folder = store.getFolder("INBOX");
+        folder.open(Folder.READ_WRITE);
+        for (Message message : folder.getMessages()) {
+            if (subject.equals(message.getSubject())) {
+                message.setFlag(Flags.Flag.DELETED, true);
+            }
+        }
+        folder.close(true);
+        store.close();
+    }
+
+    private static boolean isSeen(String subject) throws MessagingException {
+        Store store = openStore();
+        Folder folder = store.getFolder("INBOX");
+        folder.open(Folder.READ_ONLY);
+        boolean seen = false;
+        for (Message message : folder.getMessages()) {
+            if (subject.equals(message.getSubject())) {
+                seen = message.isSet(Flags.Flag.SEEN);
+            }
+        }
+        folder.close(false);
+        store.close();
+        return seen;
+    }
+
+    private static Store openStore() throws MessagingException {
+        Store store = new 
DefaultJavaMailSender().getSession().getStore("imap");
+        store.connect("localhost", Mailbox.getPort(Protocol.imap), 
kai.getLogin(), kai.getPassword());
+        return store;
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index f8768d8fd505..b5125cb94493 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -7689,6 +7689,26 @@ cannot read (with the default `skipFailedMessage=false` 
and `handleFailedMessage
 is removed, as it does without an `idempotentRepository`. Before, it failed 
only the first poll and was then skipped,
 together with the mails retrieved before it. Set `skipFailedMessage` or 
`handleFailedMessage` to skip such a mail.
 
+=== camel-mail - marking the mail of an exchange that completes after the poll
+
+The mail consumer now marks the mail of an exchange that completes after the 
poll (with `pollEnrich` or a
+`ConsumerTemplate`) against the folder in which the mail was retrieved, or 
finds it again first. Users can see these
+changes:
+
+* With `disconnect=true`, `pollEnrich` and a `ConsumerTemplate` now mark the 
mail as `SEEN` (or delete it with
+`delete=true`). Before, the mark failed with a `NullPointerException`, as the 
poll had already disconnected. The
+consumer now connects and logs in again to mark the mail, and disconnects 
again: one extra connect and login per
+completed exchange.
+* When the mark of a mail fails (for example the mail was expunged meanwhile, 
or the connection dropped), its key is now
+settled in the `idempotentRepository` as on a successful mark. With the 
default `idempotentRepositoryRemoveOnCommit=true`
+the key is removed, so when the mail is still in the folder (for example after 
the connection dropped), a later poll
+routes it again instead of skipping it as a duplicate. An expunged mail is no 
longer in the folder, so no poll routes it
+again. With `idempotentRepositoryRemoveOnCommit=false` the key is confirmed, 
and the mail stays skipped.
+* An exchange that completes after the consumer was stopped no longer marks 
its mail. Before, it opened the folder
+again, which logged in again with the credentials of the closed connection and 
left that connection open. Its key is
+settled in the same way, so with the default 
`idempotentRepositoryRemoveOnCommit=true` the mail is routed again once
+the consumer is started again.
+
 === camel-huaweicloud-smn - a Map, a List or a POJO is published as JSON, and 
the CamelHwCloudSmnMessageId property
 
 The `hwcloud-smn` producer now publishes a `Map`, a `List` or a POJO in the 
message body as JSON. Before, it published

Reply via email to