All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH kgl] Preserve original dates when importing messages over IMAP
@ 2026-10-25 18:42 James Hilliard
  2026-11-12 19:46 ` Konstantin Ryabitsev
  0 siblings, 1 reply; 8+ messages in thread
From: James Hilliard @ 2026-10-25 18:42 UTC (permalink / raw)
  To: Kernel.org Tools; +Cc: Konstantin Ryabitsev, James Hilliard

IMAP APPEND currently omits its optional timestamp, so the server assigns
the import time even when the message has a valid Date header. Archived
messages consequently appear as newly received in clients that sort by
INTERNALDATE, including the Gmail web interface.

Supply the timestamp from Date, falling back to the first parseable
Received timestamp in header order and then Delivery-date. Interpret dates
without a known timezone as UTC, consistently with the digest parser.
Retain the server-time fallback when none of these headers is usable.
Leave mbox separator dates out because public-inbox exports may use a
synthetic epoch timestamp.

Add regression coverage for header precedence, timezone offsets, folded
headers, malformed dates, fallback selection and synthetic mbox separators.
Check that choosing an APPEND date leaves the delivered message unchanged.

Signed-off-by: James Hilliard <james.hilliard1@gmail.com>
---
 src/korgalore/imap_target.py |  35 +++++++++++++-
 tests/test_imap_target.py    | 112 ++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 144 insertions(+), 3 deletions(-)

diff --git a/src/korgalore/imap_target.py b/src/korgalore/imap_target.py
index ec645e8..9065512 100644
--- a/src/korgalore/imap_target.py
+++ b/src/korgalore/imap_target.py
@@ -2,6 +2,8 @@
 
 import imaplib
 import logging
+from datetime import UTC
+from email.utils import parsedate_to_datetime
 from pathlib import Path
 from typing import Any, cast
 
@@ -12,6 +14,32 @@ from korgalore.oauth2_imap import DEFAULT_CLIENT_ID, ImapOAuth2Authenticator
 logger = logging.getLogger('korgalore')
 
 
+def _get_internaldate(msg: RawMessage) -> str:
+    """Choose an APPEND date from message headers, or leave it to the server."""
+    headers = list(msg.parsed.raw_items())
+    for field in ('date', 'received', 'delivery-date'):
+        for name, value in headers:
+            if name.lower() != field:
+                continue
+            date_value = value
+            if field == 'received':
+                # Received headers are newest first; the date follows the last ';'.
+                _, separator, date_value = value.rpartition(';')
+                if not separator:
+                    continue
+            try:
+                date = parsedate_to_datetime(date_value)
+                # Treat dates without a known timezone as UTC, as in digests.
+                if date.tzinfo is None:
+                    date = date.replace(tzinfo=UTC)
+                return imaplib.Time2Internaldate(date)
+            except (OverflowError, TypeError, ValueError):
+                continue
+    # Public-inbox mbox separators can carry a dummy epoch date, not a receipt time.
+    logger.debug('No usable message date, using server time for IMAP APPEND')
+    return ''
+
+
 class ImapTarget:
     """Target for delivering messages to IMAP mail servers."""
 
@@ -283,10 +311,13 @@ class ImapTarget:
             logger.debug('Skipping import: message %s already in folder %s', msg.message_id, effective_folder)
             return {'skipped': True}
 
+        # Preserve the message date instead of sorting archived mail by import time.
+        date_time = _get_internaldate(msg)
+
         try:
             # Append message to folder
             # flags: empty string = no flags set (message will be unread)
-            # date_time: empty string = use current time (imaplib doesn't accept None)
+            # date_time: empty string falls back to server time
             try:
                 # imaplib type stubs are incomplete - append returns (str, list[Any])
                 typ, data = cast(
@@ -294,7 +325,7 @@ class ImapTarget:
                     imap.append(
                         effective_folder,
                         '',  # No flags (empty string)
-                        '',  # Use current time (empty string for default)
+                        date_time,
                         msg.as_bytes(feed_name, delivery_name),
                     ),
                 )
diff --git a/tests/test_imap_target.py b/tests/test_imap_target.py
index cd886f6..f32dcf7 100644
--- a/tests/test_imap_target.py
+++ b/tests/test_imap_target.py
@@ -229,7 +229,7 @@ class TestImapTargetImportMessage:
             mock_imap.append.assert_not_called()
 
     def test_import_success(self, connected: tuple[ImapTarget, MagicMock]) -> None:
-        """Message is appended with no flags, current time and normalized line endings."""
+        """A message without Date uses server time and normalized line endings."""
         target, mock_imap = connected
         mock_imap.append.return_value = ('OK', [b'[APPENDUID 1234 5678]'])
         raw_message = b'From: test@example.com\nSubject: Test\n\nBody'
@@ -247,6 +247,116 @@ class TestImapTargetImportMessage:
             RawMessage(raw_message).as_bytes(),
         )
 
+    @pytest.mark.parametrize(
+        ('date_header', 'internaldate'),
+        [
+            ('Sun, 25 Oct 2026 05:10:03 +0000 (GMT)', '"25-Oct-2026 05:10:03 +0000"'),
+            ('Sun, 25 Oct 2026 10:40:03 +0530', '"25-Oct-2026 10:40:03 +0530"'),
+            ('Sat, 24 Oct 2026 22:10:03 -0700', '"24-Oct-2026 22:10:03 -0700"'),
+            ('Sun, 25 Oct 2026\n 05:10:03 +0000', '"25-Oct-2026 05:10:03 +0000"'),
+            ('Sun, 25 Oct 2026 05:10:03 -0000', '"25-Oct-2026 05:10:03 +0000"'),
+            ('Sun, 25 Oct 2026 05:10:03', '"25-Oct-2026 05:10:03 +0000"'),
+        ],
+        ids=['utc-comment', 'positive-offset', 'negative-offset', 'folded', 'unknown-zone', 'no-zone'],
+    )
+    def test_import_preserves_message_date(
+        self, connected: tuple[ImapTarget, MagicMock], date_header: str, internaldate: str
+    ) -> None:
+        """Date takes precedence over receipt time without rewriting the message."""
+        target, mock_imap = connected
+        raw_message = (
+            'From: test@example.com\n'
+            'Received: by mx.example.com; Sun, 25 Oct 2026 05:10:06 +0000\n'
+            f'Date: {date_header}\n'
+            'Delivery-date: Sun, 25 Oct 2026 05:10:10 +0000\n\nBody'
+        ).encode()
+
+        target.import_message(raw_message, [])
+
+        mock_imap.append.assert_called_once_with('INBOX', '', internaldate, RawMessage(raw_message).as_bytes())
+
+    @pytest.mark.parametrize(
+        'date_header',
+        [
+            '',
+            'not a date',
+            'Sun, 32 Oct 2026 05:10:03 +0000',
+            'Sun, 25 Oct 2026 25:10:03 +0000',
+            'Sun, 25 Oct 2026 05:10:03 +2500',
+            'Sun, 25 Oct 2026 05:10:03 +99999999999999999999',
+        ],
+        ids=['empty', 'malformed', 'invalid-day', 'invalid-hour', 'invalid-offset', 'overflow'],
+    )
+    @pytest.mark.parametrize('has_received', [False, True], ids=['server-time', 'received-time'])
+    def test_import_invalid_date_falls_back(
+        self, connected: tuple[ImapTarget, MagicMock], date_header: str, has_received: bool
+    ) -> None:
+        """An unusable Date header must not prevent message delivery."""
+        target, mock_imap = connected
+        raw_message = f'From: test@example.com\nDate: {date_header}\n'.encode()
+        if has_received:
+            raw_message += b'Received: by mx.example.com; Sun, 25 Oct 2026 05:10:06 +0000\n'
+        raw_message += b'\nBody'
+
+        target.import_message(raw_message, [])
+
+        expected = '"25-Oct-2026 05:10:06 +0000"' if has_received else ''
+        mock_imap.append.assert_called_once_with('INBOX', '', expected, RawMessage(raw_message).as_bytes())
+
+    @pytest.mark.parametrize(
+        ('received_headers', 'internaldate'),
+        [
+            (
+                'Received: by last.example.com; Sun, 25 Oct 2026 05:10:06 +0000\n'
+                'Received: by first.example.com; Sun, 25 Oct 2026 05:10:04 +0000\n',
+                '"25-Oct-2026 05:10:06 +0000"',
+            ),
+            (
+                'Received: by last.example.com; invalid\n'
+                'Received: by first.example.com; Sun, 25 Oct 2026 05:10:04 +0000\n',
+                '"25-Oct-2026 05:10:04 +0000"',
+            ),
+            (
+                'Received: from sender.example.com\n by mx.example.com;\n Sun, 25 Oct 2026 10:40:06 +0530\n',
+                '"25-Oct-2026 10:40:06 +0530"',
+            ),
+            (
+                'Received: Sun, 25 Oct 2026 05:10:06 +0000\n',
+                '"25-Oct-2026 05:10:10 +0000"',
+            ),
+            ('Received: by mx.example.com; invalid\n', '"25-Oct-2026 05:10:10 +0000"'),
+            ('', '"25-Oct-2026 05:10:10 +0000"'),
+        ],
+        ids=['latest-received', 'skip-invalid-received', 'folded', 'no-semicolon', 'invalid', 'absent'],
+    )
+    def test_import_receipt_date_fallbacks(
+        self, connected: tuple[ImapTarget, MagicMock], received_headers: str, internaldate: str
+    ) -> None:
+        """Use the first valid Received timestamp before trying Delivery-date."""
+        target, mock_imap = connected
+        raw_message = (
+            f'From: test@example.com\nDelivery-date: Sun, 25 Oct 2026 05:10:10 +0000\n{received_headers}\nBody'
+        ).encode()
+
+        target.import_message(raw_message, [])
+
+        mock_imap.append.assert_called_once_with('INBOX', '', internaldate, RawMessage(raw_message).as_bytes())
+
+    def test_import_ignores_dummy_mbox_date(self, connected: tuple[ImapTarget, MagicMock]) -> None:
+        """The archive's synthetic mbox separator is not a fallback date."""
+        target, mock_imap = connected
+        raw_message = (
+            b'From mboxrd@z Thu Jan  1 00:00:00 1970\n'
+            b'From: test@example.com\n'
+            b'Date: invalid\n'
+            b'Received: by mx.example.com; invalid\n'
+            b'Delivery-date: invalid\n\nBody'
+        )
+
+        target.import_message(raw_message, [])
+
+        mock_imap.append.assert_called_once_with('INBOX', '', '', RawMessage(raw_message).as_bytes())
+
     @pytest.mark.parametrize(
         ('folder', 'subfolder', 'expected'),
         [

---
base-commit: ea22e7c8701e566328f197c748718cd689f9ea28
change-id: 20261025-submit-imap-preserve-date-v1-f52a52f65294

Best regards,
--  
James Hilliard <james.hilliard1@gmail.com>


^ permalink raw reply related	[flat|nested] 8+ messages in thread

end of thread, other threads:[~2026-11-26 17:48 UTC | newest]

Thread overview: 8+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-10-25 18:42 [PATCH kgl] Preserve original dates when importing messages over IMAP James Hilliard
2026-11-12 19:46 ` Konstantin Ryabitsev
2026-11-12 23:07   ` James Hilliard
2026-11-16 15:06     ` Konstantin Ryabitsev
2026-11-17  2:52       ` James Hilliard
2026-11-17 14:58         ` Konstantin Ryabitsev
2026-11-17 16:53           ` James Hilliard
2026-11-26 17:48             ` Konstantin Ryabitsev

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.