Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
send_custom_email: Add support for emailing remote server contacts.
Tim Abbottaf27675857cd
diff --git a/templates/zerver/emails/custom_email_base.pre.html b/templates/zerver/emails/custom_email_base.pre.htmlindex 8d2d92277c9..05c9470b832 100644--- a/templates/zerver/emails/custom_email_base.pre.html+++ b/templates/zerver/emails/custom_email_base.pre.html@@ -12,5 +12,9 @@{% endblock %}{% block manage_preferences %}-<p><a href="{{ realm_uri }}/#settings/notifications">{{ _("Manage email preferences") }}</a> | <a href="{{ unsubscribe_link }}">{{ _("Unsubscribe from marketing emails") }}</a></p>+ {% if remote_server_email %}+ <p>You are receiving this email to update you about important changes to Zulip's Terms of Service.</p>+ {% else %}+ <p><a href="{{ realm_uri }}/#settings/notifications">{{ _("Manage email preferences") }}</a> | <a href="{{ unsubscribe_link }}">{{ _("Unsubscribe from marketing emails") }}</a></p>+ {% endif %}{% endblock %}diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.pyindex 6aabc605601..f02aabf93ba 100644--- a/zerver/lib/send_email.py+++ b/zerver/lib/send_email.py@@ -7,7 +7,7 @@ from email.headerregistry import Addressfrom email.parser import Parserfrom email.policy import defaultfrom email.utils import formataddr, parseaddr-from typing import Any, Dict, List, Mapping, Optional, Tuple+from typing import Any, Dict, List, Mapping, Optional, Sequence, Tupleimport backoffimport orjson@@ -495,8 +495,12 @@ def get_header(option: Optional[str], header: Optional[str], name: str) -> str:return str(option or header)-def send_custom_email(users: List[UserProfile], *, options: Dict[str, Any]) -> None:+def send_custom_email(+ users: List[UserProfile], *, target_emails: Sequence[str] = [], options: Dict[str, Any]+) -> None:"""+ Helper for `manage.py send_custom_email`.+Can be used directly with from a management shell withsend_custom_email(user_profile_list, dict(markdown_template_path="/path/to/markdown/file.md",@@ -566,3 +570,21 @@ def send_custom_email(users: List[UserProfile], *, options: Dict[str, Any]) -> Nif options["dry_run"]:break++ # Now send emails to any recipients without a user account.+ # This code path is intended for rare RemoteZulipServer emails.+ for email_address in target_emails:+ send_email(+ email_id,+ to_emails=[email_address],+ from_address=FromAddress.SUPPORT,+ reply_to_email=options.get("reply_to"),+ from_name=get_header(+ options.get("from_name"), parsed_email_template.get("from"), "from_name"+ ),+ context={"remote_server_email": True},+ dry_run=options["dry_run"],+ )++ if options["dry_run"]:+ breakdiff --git a/zerver/management/commands/send_custom_email.py b/zerver/management/commands/send_custom_email.pyindex 2723dbde500..93337e213e1 100644--- a/zerver/management/commands/send_custom_email.py+++ b/zerver/management/commands/send_custom_email.py@@ -1,5 +1,5 @@from argparse import ArgumentParser-from typing import Any+from typing import Any, Listfrom django.conf import settingsfrom django.core.management.base import CommandError@@ -32,6 +32,11 @@ class Command(ZulipBaseCommand):action="store_true",help="Send to active users and realm owners with the enable_marketing_emails setting enabled.",)+ parser.add_argument(+ "--remote-servers",+ action="store_true",+ help="Send to registered contact email addresses for remote Zulip servers.",+ )parser.add_argument("--markdown-template-path","--path",@@ -64,6 +69,9 @@ class Command(ZulipBaseCommand):self.add_realm_args(parser)def handle(self, *args: Any, **options: str) -> None:+ target_emails: List[str] = []+ users: List[UserProfile] = []+if options["entire_server"]:users = UserProfile.objects.filter(is_active=True, is_bot=False, is_mirror_dummy=False, realm__deactivated=False@@ -79,6 +87,14 @@ class Command(ZulipBaseCommand):enable_marketing_emails=True,long_term_idle=False,).distinct("delivery_email")+ elif options["remote_servers"]:+ from zilencer.models import RemoteZulipServer++ # TODO: Make this filter for deactivated=False once we add+ # that to the data model.+ target_emails = list(+ set(RemoteZulipServer.objects.all().values_list("contact_email", flat=True))+ )elif options["all_sponsored_org_admins"]:# Sends at most one copy to each email address, even if it# is an administrator in several organizations.@@ -114,7 +130,7 @@ class Command(ZulipBaseCommand):.filter(id__in=[u.id for u in users]).exclude(tos_version=None))- send_custom_email(users, options=options)+ send_custom_email(users, target_emails=target_emails, options=options)if options["dry_run"]:print("Would send the above email to:")diff --git a/zerver/tests/test_email_notifications.py b/zerver/tests/test_email_notifications.pyindex 1b3c0da5539..6280a28c0c8 100644--- a/zerver/tests/test_email_notifications.py+++ b/zerver/tests/test_email_notifications.py@@ -53,6 +53,36 @@ class TestCustomEmails(ZulipTestCase):self.assertEqual(msg.reply_to[0], reply_to)self.assertNotIn("{% block content %}", msg.body)+ def test_send_custom_email_remote_server(self) -> None:+ email_subject = "subject_test"+ reply_to = "reply_to_test"+ from_name = "from_name_test"+ contact_email = "[email protected]"+ markdown_template_path = "templates/corporate/policies/index.md"+ send_custom_email(+ [],+ target_emails=[contact_email],+ options={+ "markdown_template_path": markdown_template_path,+ "reply_to": reply_to,+ "subject": email_subject,+ "from_name": from_name,+ "dry_run": False,+ },+ )+ self.assert_length(mail.outbox, 1)+ msg = mail.outbox[0]+ self.assertEqual(msg.subject, email_subject)+ self.assertEqual(msg.to, [contact_email])+ self.assert_length(msg.reply_to, 1)+ self.assertEqual(msg.reply_to[0], reply_to)+ self.assertNotIn("{% block content %}", msg.body)+ # Verify that the HTML version contains the footer.+ self.assertIn(+ "You are receiving this email to update you about important changes to Zulip",+ str(msg.message()),+ )+def test_send_custom_email_headers(self) -> None:hamlet = self.example_user("hamlet")markdown_template_path = (