2020-06-11 00:54:34 +02:00
|
|
|
import datetime
|
|
|
|
import hashlib
|
|
|
|
import logging
|
|
|
|
import os
|
2020-06-05 23:26:35 +02:00
|
|
|
from email.headerregistry import Address
|
2020-06-11 00:54:34 +02:00
|
|
|
from email.parser import Parser
|
|
|
|
from email.policy import default
|
2020-06-05 23:26:35 +02:00
|
|
|
from email.utils import parseaddr
|
2020-06-11 00:54:34 +02:00
|
|
|
from typing import Any, Dict, List, Mapping, Optional, Tuple
|
|
|
|
|
|
|
|
import ujson
|
2017-05-02 01:15:58 +02:00
|
|
|
from django.conf import settings
|
2017-05-05 01:03:22 +02:00
|
|
|
from django.core.mail import EmailMultiAlternatives
|
2020-04-18 22:30:03 +02:00
|
|
|
from django.core.management import CommandError
|
2017-05-14 15:02:49 +02:00
|
|
|
from django.template import loader
|
2020-06-11 00:54:34 +02:00
|
|
|
from django.template.exceptions import TemplateDoesNotExist
|
2017-05-04 03:11:47 +02:00
|
|
|
from django.utils.timezone import now as timezone_now
|
2018-12-14 08:41:42 +01:00
|
|
|
from django.utils.translation import override as override_language
|
2020-02-14 13:58:58 +01:00
|
|
|
from django.utils.translation import ugettext as _
|
2017-05-02 01:15:58 +02:00
|
|
|
|
2018-06-08 11:06:18 +02:00
|
|
|
from confirmation.models import generate_key
|
2020-06-11 00:54:34 +02:00
|
|
|
from scripts.setup.inline_email_css import inline_template
|
|
|
|
from zerver.lib.logging_util import log_to_file
|
|
|
|
from zerver.models import EMAIL_TYPES, Realm, ScheduledEmail, UserProfile, get_user_profile_by_id
|
2017-08-28 08:41:13 +02:00
|
|
|
|
|
|
|
## Logging setup ##
|
|
|
|
|
2017-12-13 01:45:57 +01:00
|
|
|
logger = logging.getLogger('zulip.send_email')
|
|
|
|
log_to_file(logger, settings.EMAIL_LOG_PATH)
|
2017-08-28 08:41:13 +02:00
|
|
|
|
2017-11-05 11:37:41 +01:00
|
|
|
class FromAddress:
|
2017-06-26 19:43:32 +02:00
|
|
|
SUPPORT = parseaddr(settings.ZULIP_ADMINISTRATOR)[1]
|
|
|
|
NOREPLY = parseaddr(settings.NOREPLY_EMAIL_ADDRESS)[1]
|
|
|
|
|
2020-03-12 20:28:05 +01:00
|
|
|
support_placeholder = "SUPPORT"
|
|
|
|
no_reply_placeholder = 'NO_REPLY'
|
|
|
|
tokenized_no_reply_placeholder = 'TOKENIZED_NO_REPLY'
|
|
|
|
|
2018-06-08 11:06:18 +02:00
|
|
|
# Generates an unpredictable noreply address.
|
|
|
|
@staticmethod
|
|
|
|
def tokenized_no_reply_address() -> str:
|
|
|
|
if settings.ADD_TOKENS_TO_NOREPLY_ADDRESS:
|
|
|
|
return parseaddr(settings.TOKENIZED_NOREPLY_EMAIL_ADDRESS)[1].format(token=generate_key())
|
|
|
|
return FromAddress.NOREPLY
|
|
|
|
|
2020-02-14 13:58:58 +01:00
|
|
|
@staticmethod
|
|
|
|
def security_email_from_name(language: Optional[str]=None,
|
|
|
|
user_profile: Optional[UserProfile]=None) -> str:
|
|
|
|
if language is None:
|
|
|
|
assert user_profile is not None
|
|
|
|
language = user_profile.default_language
|
|
|
|
|
|
|
|
with override_language(language):
|
|
|
|
return _("Zulip Account Security")
|
|
|
|
|
2018-12-03 23:26:51 +01:00
|
|
|
def build_email(template_prefix: str, to_user_ids: Optional[List[int]]=None,
|
|
|
|
to_emails: Optional[List[str]]=None, from_name: Optional[str]=None,
|
2018-05-11 01:40:23 +02:00
|
|
|
from_address: Optional[str]=None, reply_to_email: Optional[str]=None,
|
2020-06-13 03:34:01 +02:00
|
|
|
language: Optional[str]=None, context: Mapping[str, Any]={},
|
2018-12-14 08:41:42 +01:00
|
|
|
) -> EmailMultiAlternatives:
|
2017-07-17 05:42:08 +02:00
|
|
|
# Callers should pass exactly one of to_user_id and to_email.
|
2018-12-03 23:26:51 +01:00
|
|
|
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]
|
2020-06-05 23:26:35 +02:00
|
|
|
to_emails = [str(Address(display_name=to_user.full_name, addr_spec=to_user.delivery_email)) for to_user in to_users]
|
2017-07-11 05:01:32 +02:00
|
|
|
|
2020-06-13 03:34:01 +02:00
|
|
|
context = {
|
|
|
|
**context,
|
2017-07-02 05:27:01 +02:00
|
|
|
'support_email': FromAddress.SUPPORT,
|
2017-08-16 12:10:55 +02:00
|
|
|
'email_images_base_uri': settings.ROOT_DOMAIN_URI + '/static/images/emails',
|
2017-10-19 04:09:53 +02:00
|
|
|
'physical_address': settings.PHYSICAL_ADDRESS,
|
2020-06-13 03:34:01 +02:00
|
|
|
}
|
2018-12-14 08:41:42 +01:00
|
|
|
|
|
|
|
def render_templates() -> Tuple[str, str, str]:
|
2018-12-23 19:09:04 +01:00
|
|
|
email_subject = loader.render_to_string(template_prefix + '.subject.txt',
|
|
|
|
context=context,
|
|
|
|
using='Jinja2_plaintext').strip().replace('\n', '')
|
2018-12-14 08:41:42 +01:00
|
|
|
message = loader.render_to_string(template_prefix + '.txt',
|
|
|
|
context=context, using='Jinja2_plaintext')
|
|
|
|
|
|
|
|
try:
|
|
|
|
html_message = loader.render_to_string(template_prefix + '.html', context)
|
|
|
|
except TemplateDoesNotExist:
|
|
|
|
emails_dir = os.path.dirname(template_prefix)
|
|
|
|
template = os.path.basename(template_prefix)
|
|
|
|
compiled_template_prefix = os.path.join(emails_dir, "compiled", template)
|
|
|
|
html_message = loader.render_to_string(compiled_template_prefix + '.html', context)
|
2018-12-23 19:09:04 +01:00
|
|
|
return (html_message, message, email_subject)
|
2018-12-14 08:41:42 +01:00
|
|
|
|
|
|
|
if not language and to_user_ids is not None:
|
|
|
|
language = to_users[0].default_language
|
|
|
|
if language:
|
|
|
|
with override_language(language):
|
|
|
|
# Make sure that we render the email using the target's native language
|
2018-12-23 19:09:04 +01:00
|
|
|
(html_message, message, email_subject) = render_templates()
|
2018-12-14 08:41:42 +01:00
|
|
|
else:
|
2018-12-23 19:09:04 +01:00
|
|
|
(html_message, message, email_subject) = render_templates()
|
2020-05-02 08:44:14 +02:00
|
|
|
logger.warning("Missing language for email template '%s'", template_prefix)
|
2017-06-26 19:43:32 +02:00
|
|
|
|
|
|
|
if from_name is None:
|
|
|
|
from_name = "Zulip"
|
|
|
|
if from_address is None:
|
2017-06-26 19:43:32 +02:00
|
|
|
from_address = FromAddress.NOREPLY
|
2020-03-12 20:28:05 +01:00
|
|
|
if from_address == FromAddress.tokenized_no_reply_placeholder:
|
|
|
|
from_address = FromAddress.tokenized_no_reply_address()
|
|
|
|
if from_address == FromAddress.no_reply_placeholder:
|
|
|
|
from_address = FromAddress.NOREPLY
|
|
|
|
if from_address == FromAddress.support_placeholder:
|
|
|
|
from_address = FromAddress.SUPPORT
|
|
|
|
|
2020-06-05 23:26:35 +02:00
|
|
|
from_email = str(Address(display_name=from_name, addr_spec=from_address))
|
2017-05-05 01:03:22 +02:00
|
|
|
reply_to = None
|
|
|
|
if reply_to_email is not None:
|
|
|
|
reply_to = [reply_to_email]
|
2017-07-05 08:28:43 +02:00
|
|
|
# Remove the from_name in the reply-to for noreply emails, so that users
|
|
|
|
# see "noreply@..." rather than "Zulip" or whatever the from_name is
|
|
|
|
# when they reply in their email client.
|
|
|
|
elif from_address == FromAddress.NOREPLY:
|
|
|
|
reply_to = [FromAddress.NOREPLY]
|
2017-05-05 01:03:22 +02:00
|
|
|
|
2018-12-23 19:09:04 +01:00
|
|
|
mail = EmailMultiAlternatives(email_subject, message, from_email, to_emails, reply_to=reply_to)
|
2017-05-05 01:03:22 +02:00
|
|
|
if html_message is not None:
|
|
|
|
mail.attach_alternative(html_message, 'text/html')
|
2017-06-10 06:19:32 +02:00
|
|
|
return mail
|
|
|
|
|
2017-07-12 01:05:59 +02:00
|
|
|
class EmailNotDeliveredException(Exception):
|
|
|
|
pass
|
|
|
|
|
2020-04-18 22:30:03 +02:00
|
|
|
class DoubledEmailArgumentException(CommandError):
|
2020-04-09 13:32:38 +02:00
|
|
|
def __init__(self, argument_name: str) -> None:
|
2020-06-14 02:57:50 +02:00
|
|
|
msg = f"Argument '{argument_name}' is ambiguously present in both options and email template."
|
2020-04-09 13:32:38 +02:00
|
|
|
super().__init__(msg)
|
|
|
|
|
2020-04-18 22:30:03 +02:00
|
|
|
class NoEmailArgumentException(CommandError):
|
2020-04-09 13:32:38 +02:00
|
|
|
def __init__(self, argument_name: str) -> None:
|
2020-06-14 02:57:50 +02:00
|
|
|
msg = f"Argument '{argument_name}' is required in either options or email template."
|
2020-04-09 13:32:38 +02:00
|
|
|
super().__init__(msg)
|
|
|
|
|
2017-07-02 21:10:41 +02:00
|
|
|
# When changing the arguments to this function, you may need to write a
|
|
|
|
# migration to change or remove any emails in ScheduledEmail.
|
2018-12-03 23:26:51 +01:00
|
|
|
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,
|
2018-12-14 08:41:42 +01:00
|
|
|
language: Optional[str]=None, context: Dict[str, Any]={}) -> 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)
|
2017-08-28 08:41:13 +02:00
|
|
|
template = template_prefix.split("/")[-1]
|
2020-05-02 08:44:14 +02:00
|
|
|
logger.info("Sending %s email to %s", template, mail.to)
|
2017-08-28 08:41:13 +02:00
|
|
|
|
2017-07-12 01:05:59 +02:00
|
|
|
if mail.send() == 0:
|
2020-05-02 08:44:14 +02:00
|
|
|
logger.error("Error sending %s email to %s", template, mail.to)
|
2017-07-12 01:05:59 +02:00
|
|
|
raise EmailNotDeliveredException
|
2017-05-02 01:15:58 +02:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def send_email_from_dict(email_dict: Mapping[str, Any]) -> None:
|
2017-05-05 01:31:07 +02:00
|
|
|
send_email(**dict(email_dict))
|
|
|
|
|
2018-12-03 23:26:51 +01:00
|
|
|
def send_future_email(template_prefix: str, realm: Realm, to_user_ids: Optional[List[int]]=None,
|
|
|
|
to_emails: Optional[List[str]]=None, from_name: Optional[str]=None,
|
2019-01-10 00:10:44 +01:00
|
|
|
from_address: Optional[str]=None, language: Optional[str]=None,
|
|
|
|
context: Dict[str, Any]={}, delay: datetime.timedelta=datetime.timedelta(0)) -> None:
|
2017-07-15 03:06:04 +02:00
|
|
|
template_name = template_prefix.split('/')[-1]
|
2019-03-16 02:32:43 +01:00
|
|
|
email_fields = {'template_prefix': template_prefix, 'from_name': from_name, 'from_address': from_address,
|
|
|
|
'language': language, 'context': context}
|
2017-07-15 03:06:04 +02:00
|
|
|
|
2018-12-17 13:12:54 +01:00
|
|
|
if settings.DEVELOPMENT_LOG_EMAILS:
|
2018-12-03 23:26:51 +01:00
|
|
|
send_email(template_prefix, to_user_ids=to_user_ids, to_emails=to_emails, from_name=from_name,
|
2019-01-10 00:10:44 +01:00
|
|
|
from_address=from_address, language=language, context=context)
|
2017-10-03 02:04:32 +02:00
|
|
|
# For logging the email
|
2017-09-24 00:39:19 +02:00
|
|
|
|
2018-12-03 23:26:51 +01:00
|
|
|
assert (to_user_ids is None) ^ (to_emails is None)
|
2019-01-04 01:50:21 +01:00
|
|
|
email = ScheduledEmail.objects.create(
|
2017-07-02 21:10:41 +02:00
|
|
|
type=EMAIL_TYPES[template_name],
|
|
|
|
scheduled_timestamp=timezone_now() + delay,
|
2017-12-05 03:19:48 +01:00
|
|
|
realm=realm,
|
2019-01-04 01:50:21 +01:00
|
|
|
data=ujson.dumps(email_fields))
|
|
|
|
|
2019-03-16 02:32:43 +01:00
|
|
|
# We store the recipients in the ScheduledEmail object itself,
|
|
|
|
# rather than the JSON data object, so that we can find and clear
|
|
|
|
# them using clear_scheduled_emails.
|
2019-01-04 01:50:21 +01:00
|
|
|
try:
|
|
|
|
if to_user_ids is not None:
|
|
|
|
email.users.add(*to_user_ids)
|
|
|
|
else:
|
|
|
|
assert to_emails is not None
|
|
|
|
assert(len(to_emails) == 1)
|
|
|
|
email.address = parseaddr(to_emails[0])[1]
|
|
|
|
email.save()
|
|
|
|
except Exception as e:
|
|
|
|
email.delete()
|
|
|
|
raise e
|
2018-12-03 23:26:51 +01:00
|
|
|
|
|
|
|
def send_email_to_admins(template_prefix: str, realm: Realm, from_name: Optional[str]=None,
|
2020-02-19 08:18:03 +01:00
|
|
|
from_address: Optional[str]=None, language: Optional[str]=None,
|
|
|
|
context: Dict[str, Any]={}) -> None:
|
2019-06-20 23:26:54 +02:00
|
|
|
admins = realm.get_human_admin_users()
|
2018-12-03 23:26:51 +01:00
|
|
|
admin_user_ids = [admin.id for admin in admins]
|
|
|
|
send_email(template_prefix, to_user_ids=admin_user_ids, from_name=from_name,
|
2020-02-19 08:18:03 +01:00
|
|
|
from_address=from_address, language=language, context=context)
|
2018-12-04 23:34:04 +01:00
|
|
|
|
2019-03-15 18:48:01 +01:00
|
|
|
def clear_scheduled_invitation_emails(email: str) -> None:
|
|
|
|
"""Unlike most scheduled emails, invitation emails don't have an
|
|
|
|
existing user object to key off of, so we filter by address here."""
|
|
|
|
items = ScheduledEmail.objects.filter(address__iexact=email,
|
|
|
|
type=ScheduledEmail.INVITATION_REMINDER)
|
|
|
|
items.delete()
|
|
|
|
|
|
|
|
def clear_scheduled_emails(user_ids: List[int], email_type: Optional[int]=None) -> None:
|
|
|
|
items = ScheduledEmail.objects.filter(users__in=user_ids).distinct()
|
|
|
|
if email_type is not None:
|
|
|
|
items = items.filter(type=email_type)
|
|
|
|
for item in items:
|
|
|
|
item.users.remove(*user_ids)
|
|
|
|
if item.users.all().count() == 0:
|
|
|
|
item.delete()
|
|
|
|
|
2018-12-04 23:34:04 +01:00
|
|
|
def handle_send_email_format_changes(job: Dict[str, Any]) -> None:
|
|
|
|
# Reformat any jobs that used the old to_email
|
|
|
|
# and to_user_ids argument formats.
|
|
|
|
if 'to_email' in job:
|
2018-12-14 21:43:11 +01:00
|
|
|
if job['to_email'] is not None:
|
|
|
|
job['to_emails'] = [job['to_email']]
|
2018-12-04 23:34:04 +01:00
|
|
|
del job['to_email']
|
|
|
|
if 'to_user_id' in job:
|
2018-12-14 21:43:11 +01:00
|
|
|
if job['to_user_id'] is not None:
|
|
|
|
job['to_user_ids'] = [job['to_user_id']]
|
2018-12-06 01:29:06 +01:00
|
|
|
del job['to_user_id']
|
2019-03-16 02:32:43 +01:00
|
|
|
|
|
|
|
def deliver_email(email: ScheduledEmail) -> None:
|
|
|
|
data = ujson.loads(email.data)
|
|
|
|
if email.users.exists():
|
|
|
|
data['to_user_ids'] = [user.id for user in email.users.all()]
|
|
|
|
if email.address is not None:
|
|
|
|
data['to_emails'] = [email.address]
|
|
|
|
handle_send_email_format_changes(data)
|
|
|
|
send_email(**data)
|
|
|
|
email.delete()
|
2020-04-14 19:57:09 +02:00
|
|
|
|
|
|
|
def get_header(option: Optional[str], header: Optional[str], name: str) -> str:
|
|
|
|
if option and header:
|
|
|
|
raise DoubledEmailArgumentException(name)
|
|
|
|
if not option and not header:
|
|
|
|
raise NoEmailArgumentException(name)
|
|
|
|
return str(option or header)
|
|
|
|
|
|
|
|
def send_custom_email(users: List[UserProfile], options: Dict[str, Any]) -> None:
|
|
|
|
"""
|
|
|
|
Can be used directly with from a management shell with
|
|
|
|
send_custom_email(user_profile_list, dict(
|
|
|
|
markdown_template_path="/path/to/markdown/file.md",
|
|
|
|
subject="Email Subject",
|
|
|
|
from_name="Sender Name")
|
|
|
|
)
|
|
|
|
"""
|
|
|
|
|
|
|
|
with open(options["markdown_template_path"]) as f:
|
|
|
|
text = f.read()
|
|
|
|
parsed_email_template = Parser(policy=default).parsestr(text)
|
|
|
|
email_template_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()[0:32]
|
|
|
|
|
2020-06-10 06:41:04 +02:00
|
|
|
email_filename = f"custom/custom_email_{email_template_hash}.source.html"
|
|
|
|
email_id = f"zerver/emails/custom/custom_email_{email_template_hash}"
|
2020-04-14 19:57:09 +02:00
|
|
|
markdown_email_base_template_path = "templates/zerver/emails/custom_email_base.pre.html"
|
2020-06-10 06:41:04 +02:00
|
|
|
html_source_template_path = f"templates/{email_id}.source.html"
|
|
|
|
plain_text_template_path = f"templates/{email_id}.txt"
|
|
|
|
subject_path = f"templates/{email_id}.subject.txt"
|
2020-04-22 01:48:28 +02:00
|
|
|
os.makedirs(os.path.dirname(html_source_template_path), exist_ok=True)
|
2020-04-14 19:57:09 +02:00
|
|
|
|
|
|
|
# First, we render the markdown input file just like our
|
|
|
|
# user-facing docs with render_markdown_path.
|
|
|
|
with open(plain_text_template_path, "w") as f:
|
|
|
|
f.write(parsed_email_template.get_payload())
|
|
|
|
|
|
|
|
from zerver.templatetags.app_filters import render_markdown_path
|
|
|
|
rendered_input = render_markdown_path(plain_text_template_path.replace("templates/", ""))
|
|
|
|
|
|
|
|
# And then extend it with our standard email headers.
|
|
|
|
with open(html_source_template_path, "w") as f:
|
|
|
|
with open(markdown_email_base_template_path) as base_template:
|
|
|
|
# Note that we're doing a hacky non-Jinja2 substitution here;
|
|
|
|
# we do this because the normal render_markdown_path ordering
|
|
|
|
# doesn't commute properly with inline_email_css.
|
|
|
|
f.write(base_template.read().replace('{{ rendered_input }}',
|
|
|
|
rendered_input))
|
|
|
|
|
|
|
|
with open(subject_path, "w") as f:
|
|
|
|
f.write(get_header(options.get("subject"),
|
|
|
|
parsed_email_template.get("subject"), "subject"))
|
|
|
|
|
|
|
|
inline_template(email_filename)
|
|
|
|
|
|
|
|
# Finally, we send the actual emails.
|
2020-06-10 07:28:15 +02:00
|
|
|
for user_profile in users:
|
|
|
|
if options.get('admins_only') and not user_profile.is_realm_admin:
|
|
|
|
continue
|
2020-04-14 19:57:09 +02:00
|
|
|
context = {
|
|
|
|
'realm_uri': user_profile.realm.uri,
|
|
|
|
'realm_name': user_profile.realm.name,
|
|
|
|
}
|
|
|
|
send_email(email_id, to_user_ids=[user_profile.id],
|
|
|
|
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=context)
|