Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
emails: Add a custom header specifying the organization when possible.
Mateusz Mandera9392e8bec725
diff --git a/zerver/forms.py b/zerver/forms.pyindex 2f1cc9ca1de..f99c6960c79 100644--- a/zerver/forms.py+++ b/zerver/forms.py@@ -313,7 +313,8 @@ class ZulipPasswordResetForm(PasswordResetForm):send_email('zerver/emails/password_reset', to_emails=[email],from_name=FromAddress.security_email_from_name(language=language),from_address=FromAddress.tokenized_no_reply_address(),- language=language, context=context)+ language=language, context=context,+ realm=realm)class RateLimitedPasswordResetByEmail(RateLimitedObject):def __init__(self, email: str) -> None:diff --git a/zerver/lib/actions.py b/zerver/lib/actions.pyindex 29040339300..a5d67c568c4 100644--- a/zerver/lib/actions.py+++ b/zerver/lib/actions.py@@ -994,7 +994,8 @@ def do_start_email_change_process(user_profile: UserProfile, new_email: str) ->send_email('zerver/emails/confirm_new_email', to_emails=[new_email],from_name=FromAddress.security_email_from_name(language=language),from_address=FromAddress.tokenized_no_reply_address(),- language=language, context=context)+ language=language, context=context,+ realm=user_profile.realm)def compute_irc_user_fullname(email: str) -> str:return email.split("@")[0] + " (IRC)"@@ -5074,7 +5075,8 @@ def do_send_confirmation_email(invitee: PreregistrationUser,from_name = f"{referrer.full_name} (via Zulip)"send_email('zerver/emails/invitation', to_emails=[invitee.email], from_name=from_name,from_address=FromAddress.tokenized_no_reply_address(),- language=referrer.realm.default_language, context=context)+ language=referrer.realm.default_language, context=context,+ realm=referrer.realm)return activation_urldef email_not_system_bot(email: str) -> None:diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.pyindex 6534a6dbe7f..c3f017b251c 100644--- a/zerver/lib/send_email.py+++ b/zerver/lib/send_email.py@@ -5,7 +5,7 @@ import osfrom email.headerregistry import Addressfrom email.parser import Parserfrom email.policy import default-from email.utils import parseaddr+from email.utils import formataddr, parseaddrfrom typing import Any, Dict, List, Mapping, Optional, Tupleimport ujson@@ -57,13 +57,24 @@ def build_email(template_prefix: str, to_user_ids: Optional[List[int]]=None,to_emails: Optional[List[str]]=None, from_name: Optional[str]=None,from_address: Optional[str]=None, reply_to_email: Optional[str]=None,language: Optional[str]=None, context: Mapping[str, Any]={},+ realm: Optional[Realm]=None) -> EmailMultiAlternatives:# Callers should pass exactly one of to_user_id and to_email.assert (to_user_ids is None) ^ (to_emails is None)if to_user_ids is not None:to_users = [get_user_profile_by_id(to_user_id) for to_user_id in to_user_ids]+ if realm is None:+ assert len(set([to_user.realm_id for to_user in to_users])) == 1+ realm = to_users[0].realmto_emails = [str(Address(display_name=to_user.full_name, addr_spec=to_user.delivery_email)) for to_user in to_users]+ extra_headers = {}+ if realm is not None:+ # formaddr is meant for formatting (display_name, email_address) pair for headers like "To",+ # but we can use its utility for formatting the List-Id header, as it follows the same format,+ # except having just a domain instead of an email address.+ extra_headers['List-Id'] = formataddr((realm.name, realm.host))+context = {**context,'support_email': FromAddress.SUPPORT,@@ -118,7 +129,8 @@ def build_email(template_prefix: str, to_user_ids: Optional[List[int]]=None,elif from_address == FromAddress.NOREPLY:reply_to = [FromAddress.NOREPLY]- mail = EmailMultiAlternatives(email_subject, message, from_email, to_emails, reply_to=reply_to)+ mail = EmailMultiAlternatives(email_subject, message, from_email, to_emails, reply_to=reply_to,+ headers=extra_headers)if html_message is not None:mail.attach_alternative(html_message, 'text/html')return mail@@ -141,10 +153,12 @@ class NoEmailArgumentException(CommandError):def send_email(template_prefix: str, to_user_ids: Optional[List[int]]=None,to_emails: Optional[List[str]]=None, from_name: Optional[str]=None,from_address: Optional[str]=None, reply_to_email: Optional[str]=None,- language: Optional[str]=None, context: Dict[str, Any]={}) -> None:+ language: Optional[str]=None, context: Dict[str, Any]={},+ realm: Optional[Realm]=None) -> None:mail = build_email(template_prefix, to_user_ids=to_user_ids, to_emails=to_emails,from_name=from_name, from_address=from_address,- reply_to_email=reply_to_email, language=language, context=context)+ reply_to_email=reply_to_email, language=language, context=context,+ realm=realm)template = template_prefix.split("/")[-1]logger.info("Sending %s email to %s", template, mail.to)diff --git a/zerver/tests/test_email_change.py b/zerver/tests/test_email_change.pyindex 08dead6ffb5..ddc0fc0c7b2 100644--- a/zerver/tests/test_email_change.py+++ b/zerver/tests/test_email_change.py@@ -108,6 +108,8 @@ class EmailChangeTestCase(ZulipTestCase):fr"^Zulip Account Security <{self.TOKENIZED_NOREPLY_REGEX}>\Z",)+ self.assertEqual(email_message.extra_headers["List-Id"], "Zulip Dev <zulip.testserver>")+activation_url = [s for s in body.split('\n') if s][2]response = self.client_get(activation_url)diff --git a/zerver/tests/test_email_notifications.py b/zerver/tests/test_email_notifications.pyindex 75a5186a3ad..822f57f222c 100644--- a/zerver/tests/test_email_notifications.py+++ b/zerver/tests/test_email_notifications.py@@ -251,6 +251,8 @@ class TestMissedMessages(ZulipTestCase):for text in verify_body_does_not_include:self.assertNotIn(text, self.normalize_string(msg.body))+ self.assertEqual(msg.extra_headers["List-Id"], "Zulip Dev <zulip.testserver>")+def _realm_name_in_missed_message_email_subject(self, realm_name_in_notifications: bool) -> None:msg_id = self.send_personal_message(self.example_user('othello'),diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.pyindex 6c6388b332e..6310056eecb 100644--- a/zerver/tests/test_signup.py+++ b/zerver/tests/test_signup.py@@ -236,13 +236,15 @@ class PasswordResetTest(ZulipTestCase):Log in, reset password, log out, log in with new password."""- def get_reset_mail_body(self) -> str:+ def get_reset_mail_body(self, subdomain: str='zulip') -> str:from django.core.mail import outbox[message] = outboxself.assertRegex(message.from_email,fr"^Zulip Account Security <{self.TOKENIZED_NOREPLY_REGEX}>\Z",)+ self.assertIn(f"{subdomain}.testserver", message.extra_headers["List-Id"])+return message.bodydef test_password_reset(self) -> None:@@ -421,7 +423,7 @@ class PasswordResetTest(ZulipTestCase):self.assert_in_response("Check your email in a few minutes to finish the process.", result)- body = self.get_reset_mail_body()+ body = self.get_reset_mail_body('zephyr')self.assertIn('Somebody (possibly you) requested a new password', body)self.assertIn('You do not have an account', body)self.assertIn("active accounts in the following organization(s).\nhttp://zulip.testserver",@@ -759,6 +761,8 @@ class InviteUserBase(ZulipTestCase):self.assertRegex(outbox[0].from_email, fr" <{self.TOKENIZED_NOREPLY_REGEX}>\Z")+ self.assertEqual(outbox[0].extra_headers["List-Id"], "Zulip Dev <zulip.testserver>")+def invite(self, invitee_emails: str, stream_names: Sequence[str], body: str='',invite_as: int=PreregistrationUser.INVITE_AS['MEMBER']) -> HttpResponse:"""@@ -2782,6 +2786,19 @@ class UserSignUpTest(InviteUserBase):# Verify that the user is asked for name and passwordself.assert_in_success_response(['id_password', 'id_full_name'], result)+ def test_signup_email_message_contains_org_header(self) -> None:+ email = "[email protected]"++ result = self.client_post('/accounts/home/', {'email': email})+ self.assertEqual(result.status_code, 302)+ self.assertTrue(result["Location"].endswith(+ f"/accounts/send_confirm/{email}"))+ result = self.client_get(result["Location"])+ self.assert_in_response("Check your email so we can get started.", result)++ from django.core.mail import outbox+ self.assertEqual(outbox[0].extra_headers["List-Id"], "Zulip Dev <zulip.testserver>")+def test_signup_with_full_name(self) -> None:"""Check if signing up without a full name redirects to a registrationdiff --git a/zerver/views/registration.py b/zerver/views/registration.pyindex b095453db3d..b43db0c25bf 100644--- a/zerver/views/registration.py+++ b/zerver/views/registration.py@@ -476,10 +476,12 @@ def prepare_activation_url(email: str, request: HttpRequest,request.session['confirmation_key'] = {'confirmation_key': activation_url.split('/')[-1]}return activation_url-def send_confirm_registration_email(email: str, activation_url: str, language: str) -> None:+def send_confirm_registration_email(email: str, activation_url: str, language: str,+ realm: Optional[Realm]=None) -> None:send_email('zerver/emails/confirm_registration', to_emails=[email],from_address=FromAddress.tokenized_no_reply_address(),- language=language, context={'activate_url': activation_url})+ language=language, context={'activate_url': activation_url},+ realm=realm)def redirect_to_email_login_url(email: str) -> HttpResponseRedirect:login_url = reverse('django.contrib.auth.views.login')@@ -556,7 +558,7 @@ def accounts_home(request: HttpRequest, multiuse_object_key: str="",activation_url = prepare_activation_url(email, request, streams=streams_to_subscribe,invited_as=invited_as)try:- send_confirm_registration_email(email, activation_url, request.LANGUAGE_CODE)+ send_confirm_registration_email(email, activation_url, request.LANGUAGE_CODE, realm=realm)except smtplib.SMTPException as e:logging.error('Error in accounts_home: %s', str(e))return HttpResponseRedirect("/config-error/smtp")diff --git a/zerver/views/user_settings.py b/zerver/views/user_settings.pyindex db10ab43769..e4fffc76440 100644--- a/zerver/views/user_settings.py+++ b/zerver/views/user_settings.py@@ -65,7 +65,8 @@ def confirm_email_change(request: HttpRequest, confirmation_key: str) -> HttpRessend_email('zerver/emails/notify_change_in_email', to_emails=[old_email],from_name=FromAddress.security_email_from_name(user_profile=user_profile),from_address=FromAddress.SUPPORT, language=language,- context=context)+ context=context,+ realm=user_profile.realm)ctx = {'new_email': new_email,