fix: never restore deleted mails during sync — deleted means deleted

- Sync was restoring deleted_at mails when found on IMAP server
- This caused deleted mails to reappear in inbox on every sync
- Now deleted mails are always skipped during sync, never restored
- IMAP delete is retried via sync queue
This commit is contained in:
Agent Zero
2026-07-20 14:26:07 +02:00
parent c846a2e158
commit 452828babe
+7 -28
View File
@@ -665,21 +665,11 @@ async def imap_sync_folder(
).scalar_one_or_none()
if existing_mail:
# If mail has deleted_at but is still on the IMAP server,
# the IMAP delete failed.
# Only restore if the mail is in the SAME folder we're syncing.
# If the mail was moved to Trash in DB (folder_id=Trash) but is
# still in INBOX on IMAP, DON'T restore to INBOX — keep it
# in Trash and let the sync queue retry the IMAP MOVE.
# If mail has deleted_at, it was deleted in LeoCRM.
# DO NOT restore it — keep it deleted and let the sync queue
# retry the IMAP delete/move. This prevents deleted mails from
# reappearing in the inbox.
if existing_mail.deleted_at is not None:
if existing_mail.folder_id == folder.id:
# Mail is in the right folder on IMAP — restore
existing_mail.deleted_at = None
logger.info("imap_sync_folder: restored mail %s (still on IMAP server in correct folder)", existing_mail.id)
else:
# Mail is in a different folder in DB — IMAP move failed
# Don't restore, don't change folder_id — keep in Trash
logger.info("imap_sync_folder: skipping mail %s (deleted, in folder %s but found in %s on IMAP, move failed)", existing_mail.id, existing_mail.folder_id, folder.imap_name)
continue
# Update folder_id and imap_uid if mail moved to a different folder
if existing_mail.folder_id != folder.id:
@@ -1174,21 +1164,10 @@ async def imap_sync_account(
).scalar_one_or_none()
if existing_mail:
# If mail has deleted_at but is still on the IMAP server,
# the IMAP delete failed.
# Only restore if the mail is in the SAME folder we're syncing.
# If the mail was moved to Trash in DB (folder_id=Trash) but is
# still in INBOX on IMAP, DON'T restore to INBOX — keep it
# in Trash and let the sync queue retry the IMAP MOVE.
# If mail has deleted_at, it was deleted in LeoCRM.
# DO NOT restore it — keep it deleted and let the sync queue
# retry the IMAP delete/move.
if existing_mail.deleted_at is not None:
if existing_mail.folder_id == folder.id:
# Mail is in the right folder on IMAP — restore
existing_mail.deleted_at = None
logger.info("imap_sync_account: restored mail %s (still on IMAP server in correct folder)", existing_mail.id)
else:
# Mail is in a different folder in DB — IMAP move failed
# Don't restore, don't change folder_id — keep in Trash
logger.info("imap_sync_account: skipping mail %s (deleted, in folder %s but found in %s on IMAP, move failed)", existing_mail.id, existing_mail.folder_id, folder.imap_name)
continue
# Track folder moves: update folder_id and imap_uid if the
# mail now appears in a different IMAP folder.