-
Notifications
You must be signed in to change notification settings - Fork 13.9k
/
email.py
236 lines (209 loc) · 7.27 KB
/
email.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import textwrap
from dataclasses import dataclass
from email.utils import make_msgid, parseaddr
from typing import Any, Optional
import nh3
from flask_babel import gettext as __
from superset import app
from superset.exceptions import SupersetErrorsException
from superset.reports.models import ReportRecipientType
from superset.reports.notifications.base import BaseNotification
from superset.reports.notifications.exceptions import NotificationError
from superset.utils import json
from superset.utils.core import HeaderDataType, send_email_smtp
from superset.utils.decorators import statsd_gauge
logger = logging.getLogger(__name__)
TABLE_TAGS = {"table", "th", "tr", "td", "thead", "tbody", "tfoot"}
TABLE_ATTRIBUTES = {"colspan", "rowspan", "halign", "border", "class"}
ALLOWED_TAGS = {
"a",
"abbr",
"acronym",
"b",
"blockquote",
"br",
"code",
"div",
"em",
"i",
"li",
"ol",
"p",
"strong",
"ul",
}.union(TABLE_TAGS)
ALLOWED_TABLE_ATTRIBUTES = {tag: TABLE_ATTRIBUTES for tag in TABLE_TAGS}
ALLOWED_ATTRIBUTES = {
"a": {"href", "title"},
"abbr": {"title"},
"acronym": {"title"},
**ALLOWED_TABLE_ATTRIBUTES,
}
@dataclass
class EmailContent:
body: str
header_data: Optional[HeaderDataType] = None
data: Optional[dict[str, Any]] = None
pdf: Optional[dict[str, bytes]] = None
images: Optional[dict[str, bytes]] = None
class EmailNotification(BaseNotification): # pylint: disable=too-few-public-methods
"""
Sends an email notification for a report recipient
"""
type = ReportRecipientType.EMAIL
@staticmethod
def _get_smtp_domain() -> str:
return parseaddr(app.config["SMTP_MAIL_FROM"])[1].split("@")[1]
@staticmethod
def _error_template(text: str) -> str:
return __(
"""
Error: %(text)s
""",
text=text,
)
def _get_content(self) -> EmailContent:
if self._content.text:
return EmailContent(body=self._error_template(self._content.text))
# Get the domain from the 'From' address ..
# and make a message id without the < > in the end
domain = self._get_smtp_domain()
images = {}
if self._content.screenshots:
images = {
make_msgid(domain)[1:-1]: screenshot
for screenshot in self._content.screenshots
}
# Strip any malicious HTML from the description
# pylint: disable=no-member
description = nh3.clean(
self._content.description or "",
tags=ALLOWED_TAGS,
attributes=ALLOWED_ATTRIBUTES,
)
# Strip malicious HTML from embedded data, allowing only table elements
if self._content.embedded_data is not None:
df = self._content.embedded_data
# pylint: disable=no-member
html_table = nh3.clean(
df.to_html(na_rep="", index=True, escape=True),
# pandas will escape the HTML in cells already, so passing
# more allowed tags here will not work
tags=TABLE_TAGS,
attributes=ALLOWED_TABLE_ATTRIBUTES,
)
else:
html_table = ""
call_to_action = __(app.config["EMAIL_REPORTS_CTA"])
img_tags = []
for msgid in images.keys():
img_tags.append(
f"""<div class="image">
<img width="1000" src="cid:{msgid}">
</div>
"""
)
img_tag = "".join(img_tags)
body = textwrap.dedent(
f"""
<html>
<head>
<style type="text/css">
table, th, td {{
border-collapse: collapse;
border-color: rgb(200, 212, 227);
color: rgb(42, 63, 95);
padding: 4px 8px;
}}
.image{{
margin-bottom: 18px;
min-width: 1000px;
}}
</style>
</head>
<body>
<div>{description}</div>
<br>
<b><a href="{self._content.url}">{call_to_action}</a></b><p></p>
{html_table}
{img_tag}
</body>
</html>
"""
)
csv_data = None
if self._content.csv:
csv_data = {__("%(name)s.csv", name=self._content.name): self._content.csv}
pdf_data = None
if self._content.pdf:
pdf_data = {__("%(name)s.pdf", name=self._content.name): self._content.pdf}
return EmailContent(
body=body,
images=images,
pdf=pdf_data,
data=csv_data,
header_data=self._content.header_data,
)
def _get_subject(self) -> str:
return __(
"%(prefix)s %(title)s",
prefix=app.config["EMAIL_REPORTS_SUBJECT_PREFIX"],
title=self._content.name,
)
def _get_to(self) -> str:
return json.loads(self._recipient.recipient_config_json)["target"]
def _get_cc(self) -> str:
# To accomadate backward compatability
return json.loads(self._recipient.recipient_config_json).get("ccTarget", "")
def _get_bcc(self) -> str:
# To accomadate backward compatability
return json.loads(self._recipient.recipient_config_json).get("bccTarget", "")
@statsd_gauge("reports.email.send")
def send(self) -> None:
subject = self._get_subject()
content = self._get_content()
to = self._get_to()
cc = self._get_cc()
bcc = self._get_bcc()
try:
send_email_smtp(
to,
subject,
content.body,
app.config,
files=[],
data=content.data,
pdf=content.pdf,
images=content.images,
mime_subtype="related",
dryrun=False,
cc=cc,
bcc=bcc,
header_data=content.header_data,
)
logger.info(
"Report sent to email, notification content is %s", content.header_data
)
except SupersetErrorsException as ex:
raise NotificationError(
";".join([error.message for error in ex.errors])
) from ex
except Exception as ex:
raise NotificationError(str(ex)) from ex