Skip to content

Commit d9e62c6

Browse files
jbkjrJack Kochclaude
authored
Fix: Sort emails by date instead of UID order (#98)
The order parameter was sorting by IMAP UID order, which doesn't guarantee chronological order on all servers. ProtonMail Bridge (and potentially others) assign UIDs in non-chronological order, causing order=desc to return oldest emails instead of newest. This fix: - Fetches metadata for all matching emails - Sorts by the actual email Date header - Applies pagination after sorting Fixes #97 Co-authored-by: Jack Koch <jack@jbkjr.me> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
1 parent 72b2d59 commit d9e62c6

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

mcp_email_server/emails/classic.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -267,14 +267,12 @@ async def get_emails_metadata_stream( # noqa: C901
267267
else:
268268
email_ids = messages[0].split()
269269
logger.info(f"Found {len(email_ids)} email IDs")
270-
start = (page - 1) * page_size
271-
end = start + page_size
272-
273-
if order == "desc":
274-
email_ids.reverse()
270+
# Fetch metadata for all emails first, then sort by date
271+
# (UID order doesn't guarantee chronological order on all IMAP servers)
272+
all_metadata: list[dict[str, Any]] = []
275273

276274
# Fetch each message's metadata only
277-
for _, email_id in enumerate(email_ids[start:end]):
275+
for _, email_id in enumerate(email_ids):
278276
try:
279277
# Convert email_id from bytes to string
280278
email_id_str = email_id.decode("utf-8")
@@ -343,14 +341,23 @@ async def get_emails_metadata_stream( # noqa: C901
343341
"date": date,
344342
"attachments": [], # We don't fetch attachment info for metadata
345343
}
346-
yield metadata
344+
all_metadata.append(metadata)
347345
except Exception as e:
348346
# Log error but continue with other emails
349347
logger.error(f"Error parsing email metadata: {e!s}")
350348
else:
351349
logger.error(f"Could not find header data in response for email ID: {email_id_str}")
352350
except Exception as e:
353351
logger.error(f"Error fetching email metadata {email_id}: {e!s}")
352+
353+
# Sort by date (desc = newest first, asc = oldest first)
354+
all_metadata.sort(key=lambda x: x["date"], reverse=(order == "desc"))
355+
356+
# Apply pagination after sorting
357+
start = (page - 1) * page_size
358+
end = start + page_size
359+
for metadata in all_metadata[start:end]:
360+
yield metadata
354361
finally:
355362
# Ensure we logout properly
356363
try:

0 commit comments

Comments
 (0)