Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
missedmessage_email: Add 'In-Reply-To' and 'References' headers.
Prakhar Pratyush7b428d631f29
diff --git a/zerver/lib/email_notifications.py b/zerver/lib/email_notifications.pyindex 9a859d85f11..c36a61c50aa 100644--- a/zerver/lib/email_notifications.py+++ b/zerver/lib/email_notifications.py@@ -1,5 +1,6 @@# See https://zulip.readthedocs.io/en/latest/subsystems/notifications.html+import base64import loggingimport osimport re@@ -405,6 +406,39 @@ def include_realm_name_in_missedmessage_emails_subject(user_profile: UserProfile)+def prepare_synthetic_root_message_id(+ recipient_type: int,+ recipient_id: int,+ *,+ dm_sender_id: int | None = None,+ topic_name: str | None = None,+) -> str:+ """+ To help email clients thread messages from the same conversation together,+ we treat all messages as replies to a synthetic root message. This root+ message's `Message-ID` header is derived from the recipient_id (and sender_id or topic),+ ensuring consistency across all emails in the thread.+ """+ if recipient_type == Recipient.PERSONAL:+ assert dm_sender_id is not None+ id_left = f"{recipient_id}.{dm_sender_id}"+ elif recipient_type == Recipient.DIRECT_MESSAGE_GROUP:+ id_left = f"{recipient_id}"+ else:+ assert topic_name is not None+ # Base64-encode the topic name b/c as per RFC 5322, <id_left> needs to be a dot-atom-text.+ # dot-atom-text = 1*atext *("." 1*atext)+ # atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" /+ # "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~"+ # ref:+ # - https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.4+ # - https://datatracker.ietf.org/doc/html/rfc5322#section-3.2.3+ topic_name_base64 = base64.b64encode(topic_name.encode("utf-8")).decode("utf-8")+ id_left = f"{recipient_id}.{topic_name_base64}"++ return f"<{id_left}@{settings.EXTERNAL_HOST_WITHOUT_PORT}>"++def do_send_missedmessage_events_reply_in_zulip(user_profile: UserProfile, missed_messages: list[dict[str, Any]], message_count: int) -> None:@@ -528,6 +562,9 @@ def do_send_missedmessage_events_reply_in_zulip(", ".join(other_recipients[:2]), len(other_recipients) - 2)context.update(group_pm=True, direct_message_group_display_name=group_display_name)+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.DIRECT_MESSAGE_GROUP, message.recipient_id+ )elif message.recipient.type == Recipient.PERSONAL:narrow_url = personal_narrow_url(realm=user_profile.realm,@@ -535,6 +572,9 @@ def do_send_missedmessage_events_reply_in_zulip(sender_full_name=message.sender.full_name,)context.update(narrow_url=narrow_url, private_message=True)+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.PERSONAL, message.recipient_id, dm_sender_id=message.sender.id+ )elif (context["mention"]or context["stream_email_notify"]@@ -569,6 +609,9 @@ def do_send_missedmessage_events_reply_in_zulip(topic_name=display_topic_name,topic_resolved=topic_resolved,)+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.STREAM, message.recipient_id, topic_name=display_topic_name.lower()+ )else:raise AssertionError("Invalid messages!")@@ -617,6 +660,8 @@ def do_send_missedmessage_events_reply_in_zulip("reply_to_email": str(Address(display_name=reply_to_name, addr_spec=reply_to_address)),"context": context,"date": email_format_datetime(local_time),+ "in_reply_to": synthetic_root_message_id,+ "references": synthetic_root_message_id,}queue_event_on_commit("email_senders", email_dict)diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.pyindex fcb56941cb5..91a8e23d097 100644--- a/zerver/lib/send_email.py+++ b/zerver/lib/send_email.py@@ -99,6 +99,8 @@ def build_email(date: str | None = None,context: Mapping[str, Any] = {},realm: Realm | None = None,+ in_reply_to: str | None = None,+ references: str | None = None,) -> EmailMultiAlternatives:# Callers should pass exactly one of to_user_id and to_email.assert (to_user_ids is None) ^ (to_emails is None)@@ -141,6 +143,12 @@ def build_email(# except having just a domain instead of an email address.extra_headers["List-Id"] = formataddr((realm.name, realm.host))+ if in_reply_to is not None:+ extra_headers["In-Reply-To"] = in_reply_to++ if references is not None:+ extra_headers["References"] = references+assert settings.STATIC_URL is not Nonecontext = {**context,@@ -272,6 +280,8 @@ def send_immediate_email(connection: BaseEmailBackend | None = None,dry_run: bool = False,request: HttpRequest | None = None,+ in_reply_to: str | None = None,+ references: str | None = None,) -> None:mail = build_email(template_prefix,@@ -284,6 +294,8 @@ def send_immediate_email(date=date,context=context,realm=realm,+ in_reply_to=in_reply_to,+ references=references,)template = template_prefix.split("/")[-1]diff --git a/zerver/tests/test_message_notification_emails.py b/zerver/tests/test_message_notification_emails.pyindex d1fb60393fd..7c7d1d440ce 100644--- a/zerver/tests/test_message_notification_emails.py+++ b/zerver/tests/test_message_notification_emails.py@@ -1,3 +1,4 @@+import base64import randomimport refrom collections.abc import Sequence@@ -26,6 +27,7 @@ from zerver.lib.email_notifications import (fix_spoilers_in_html,handle_missedmessage_emails,include_realm_name_in_missedmessage_emails_subject,+ prepare_synthetic_root_message_id,relative_to_full_url,)from zerver.lib.emoji import get_emoji_file_name@@ -34,7 +36,7 @@ from zerver.lib.test_classes import ZulipTestCasefrom zerver.models import Message, UserMessage, UserProfile, UserTopicfrom zerver.models.realm_emoji import get_name_keyed_dict_for_active_realm_emojifrom zerver.models.realms import get_realm-from zerver.models.recipients import get_or_create_direct_message_group+from zerver.models.recipients import Recipient, get_or_create_direct_message_groupfrom zerver.models.scheduled_jobs import NotificationTriggersfrom zerver.models.streams import get_stream@@ -1997,3 +1999,91 @@ class TestMessageNotificationEmails(ZulipTestCase):expected_email_body_includes = f"You are receiving this because all topic participants were mentioned in #Denmark > {Message.EMPTY_TOPIC_FALLBACK_NAME}."self.assertEqual(mail.outbox[0].subject, expected_email_subject)self.assertIn(expected_email_body_includes, self.normalize_string(mail.outbox[0].body))++ def test_prepare_synthetic_root_message_id(self) -> None:+ hamlet = self.example_user("hamlet")+ aaron = self.example_user("aaron")+ cordelia = self.example_user("cordelia")+ othello = self.example_user("othello")++ # Verify different `synthetic_root_message_id` for different 1:1 DM to hamlet.+ message_id = self.send_personal_message(aaron, hamlet)+ recipient_id = Message.objects.get(id=message_id).recipient_id+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.PERSONAL, recipient_id, dm_sender_id=aaron.id+ )+ self.assertEqual(synthetic_root_message_id, f"<{recipient_id}.{aaron.id}@testserver>")++ message_id = self.send_personal_message(cordelia, hamlet)+ recipient_id = Message.objects.get(id=message_id).recipient_id+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.PERSONAL, recipient_id, dm_sender_id=cordelia.id+ )+ self.assertEqual(synthetic_root_message_id, f"<{recipient_id}.{cordelia.id}@testserver>")++ # Verify different `synthetic_root_message_id` for different group-DM to hamlet.+ message_id = self.send_group_direct_message(aaron, [hamlet, cordelia], "Group DM!")+ recipient_id = Message.objects.get(id=message_id).recipient_id+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.DIRECT_MESSAGE_GROUP, recipient_id+ )+ self.assertEqual(synthetic_root_message_id, f"<{recipient_id}@testserver>")++ message_id = self.send_group_direct_message(aaron, [hamlet, cordelia, othello], "Group DM!")+ recipient_id = Message.objects.get(id=message_id).recipient_id+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.DIRECT_MESSAGE_GROUP, recipient_id+ )+ expected_synthetic_root_message_id = f"<{recipient_id}@testserver>"+ self.assertEqual(synthetic_root_message_id, expected_synthetic_root_message_id)++ # Changing the sender in a group DM doesn't alter `synthetic_root_message_id`.+ message_id = self.send_group_direct_message(othello, [hamlet, cordelia, aaron], "Group DM!")+ recipient_id = Message.objects.get(id=message_id).recipient_id+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.DIRECT_MESSAGE_GROUP, recipient_id+ )+ self.assertEqual(synthetic_root_message_id, expected_synthetic_root_message_id)++ # Verify different `synthetic_root_message_id` for different topics.+ topic_name = "test"+ message_id = self.send_stream_message(othello, "Denmark", topic_name=topic_name)+ recipient_id = Message.objects.get(id=message_id).recipient_id+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.STREAM, recipient_id, topic_name=topic_name+ )+ topic_name_base64 = base64.b64encode(topic_name.encode("utf-8")).decode("utf-8")+ self.assertEqual(+ synthetic_root_message_id, f"<{recipient_id}.{topic_name_base64}@testserver>"+ )++ topic_name = "hello world"+ message_id = self.send_stream_message(aaron, "Verona", topic_name=topic_name)+ recipient_id = Message.objects.get(id=message_id).recipient_id+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.STREAM, recipient_id, topic_name=topic_name+ )+ topic_name_base64 = base64.b64encode(topic_name.encode("utf-8")).decode("utf-8")+ expected_synthetic_root_message_id = f"<{recipient_id}.{topic_name_base64}@testserver>"+ self.assertEqual(synthetic_root_message_id, expected_synthetic_root_message_id)++ # Same `synthetic_root_message_id` for messages in the same conversation.+ message_id = self.send_stream_message(cordelia, "Verona", topic_name=topic_name)+ recipient_id = Message.objects.get(id=message_id).recipient_id+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.STREAM, recipient_id, topic_name=topic_name+ )+ self.assertEqual(synthetic_root_message_id, expected_synthetic_root_message_id)++ # Verify only Printable US-ASCII, exactly one '@', no spaces.+ topic_name = "中文 @ zulip 🐙"+ message_id = self.send_stream_message(othello, "Denmark", topic_name=topic_name)+ recipient_id = Message.objects.get(id=message_id).recipient_id+ synthetic_root_message_id = prepare_synthetic_root_message_id(+ Recipient.STREAM, recipient_id, topic_name=topic_name+ )+ self.assertTrue(+ synthetic_root_message_id.isascii() and synthetic_root_message_id.isprintable()+ )+ self.assertEqual(synthetic_root_message_id.count("@"), 1)+ self.assertNotIn(" ", synthetic_root_message_id)