Set correct timezone when rendering emails

This commit is contained in:
Raphael Michel
2021-03-26 12:47:36 +01:00
parent 2c2a7e07f0
commit 5be09accf7

View File

@@ -11,6 +11,7 @@ from typing import Any, Dict, List, Sequence, Union
from urllib.parse import urljoin, urlparse from urllib.parse import urljoin, urlparse
import cssutils import cssutils
import pytz
import requests import requests
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from celery import chain from celery import chain
@@ -21,6 +22,7 @@ from django.core.mail import (
from django.core.mail.message import SafeMIMEText from django.core.mail.message import SafeMIMEText
from django.db import transaction from django.db import transaction
from django.template.loader import get_template from django.template.loader import get_template
from django.utils.timezone import override
from django.utils.translation import gettext as _, pgettext from django.utils.translation import gettext as _, pgettext
from django_scopes import scope, scopes_disabled from django_scopes import scope, scopes_disabled
from i18nfield.strings import LazyI18nString from i18nfield.strings import LazyI18nString
@@ -145,6 +147,7 @@ def mail(email: Union[str, Sequence[str]], subject: str, template: Union[str, La
bcc = [] bcc = []
if event: if event:
timezone = event.timezone
renderer = event.get_html_mail_renderer() renderer = event.get_html_mail_renderer()
if event.settings.mail_bcc: if event.settings.mail_bcc:
for bcc_mail in event.settings.mail_bcc.split(','): for bcc_mail in event.settings.mail_bcc.split(','):
@@ -203,19 +206,24 @@ def mail(email: Union[str, Sequence[str]], subject: str, template: Union[str, La
) )
) )
body_plain += "\r\n" body_plain += "\r\n"
elif user:
timezone = pytz.timezone(user.timezone)
else:
timezone = pytz.timezone(settings.TIME_ZONE)
try: with override(timezone):
if 'position' in inspect.signature(renderer.render).parameters: try:
body_html = renderer.render(content_plain, signature, raw_subject, order, position) if 'position' in inspect.signature(renderer.render).parameters:
else: body_html = renderer.render(content_plain, signature, raw_subject, order, position)
# Backwards compatibility else:
warnings.warn('E-mail renderer called without position argument because position argument is not ' # Backwards compatibility
'supported.', warnings.warn('E-mail renderer called without position argument because position argument is not '
DeprecationWarning) 'supported.',
body_html = renderer.render(content_plain, signature, raw_subject, order) DeprecationWarning)
except: body_html = renderer.render(content_plain, signature, raw_subject, order)
logger.exception('Could not render HTML body') except:
body_html = None logger.exception('Could not render HTML body')
body_html = None
send_task = mail_send_task.si( send_task = mail_send_task.si(
to=[email] if isinstance(email, str) else list(email), to=[email] if isinstance(email, str) else list(email),