email_utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. import email
  2. import os
  3. from email.header import decode_header
  4. from email.message import Message
  5. from email.mime.base import MIMEBase
  6. from email.mime.multipart import MIMEMultipart
  7. from email.mime.text import MIMEText
  8. from email.utils import make_msgid, formatdate, parseaddr
  9. from smtplib import SMTP
  10. from typing import Optional
  11. import re
  12. import arrow
  13. import dkim
  14. from jinja2 import Environment, FileSystemLoader
  15. from app.config import (
  16. SUPPORT_EMAIL,
  17. ROOT_DIR,
  18. POSTFIX_SERVER,
  19. NOT_SEND_EMAIL,
  20. DKIM_SELECTOR,
  21. DKIM_PRIVATE_KEY,
  22. DKIM_HEADERS,
  23. ALIAS_DOMAINS,
  24. SUPPORT_NAME,
  25. POSTFIX_SUBMISSION_TLS,
  26. MAX_NB_EMAIL_FREE_PLAN,
  27. DISPOSABLE_EMAIL_DOMAINS,
  28. MAX_ALERT_24H,
  29. POSTFIX_PORT,
  30. SENDER,
  31. URL,
  32. LANDING_PAGE_URL,
  33. )
  34. from app.dns_utils import get_mx_domains
  35. from app.extensions import db
  36. from app.log import LOG
  37. from app.models import Mailbox, User, SentAlert
  38. def render(template_name, **kwargs) -> str:
  39. templates_dir = os.path.join(ROOT_DIR, "templates", "emails")
  40. env = Environment(loader=FileSystemLoader(templates_dir))
  41. template = env.get_template(template_name)
  42. return template.render(
  43. MAX_NB_EMAIL_FREE_PLAN=MAX_NB_EMAIL_FREE_PLAN,
  44. URL=URL,
  45. LANDING_PAGE_URL=LANDING_PAGE_URL,
  46. **kwargs,
  47. )
  48. def send_welcome_email(user):
  49. send_email(
  50. user.email,
  51. f"Welcome to SimpleLogin {user.name}",
  52. render("com/welcome.txt", name=user.name, user=user),
  53. render("com/welcome.html", name=user.name, user=user),
  54. )
  55. def send_trial_end_soon_email(user):
  56. send_email(
  57. user.email,
  58. f"Your trial will end soon {user.name}",
  59. render("transactional/trial-end.txt", name=user.name, user=user),
  60. render("transactional/trial-end.html", name=user.name, user=user),
  61. )
  62. def send_activation_email(email, name, activation_link):
  63. send_email(
  64. email,
  65. f"Just one more step to join SimpleLogin {name}",
  66. render(
  67. "transactional/activation.txt",
  68. name=name,
  69. activation_link=activation_link,
  70. email=email,
  71. ),
  72. render(
  73. "transactional/activation.html",
  74. name=name,
  75. activation_link=activation_link,
  76. email=email,
  77. ),
  78. )
  79. def send_reset_password_email(email, name, reset_password_link):
  80. send_email(
  81. email,
  82. f"Reset your password on SimpleLogin",
  83. render(
  84. "transactional/reset-password.txt",
  85. name=name,
  86. reset_password_link=reset_password_link,
  87. ),
  88. render(
  89. "transactional/reset-password.html",
  90. name=name,
  91. reset_password_link=reset_password_link,
  92. ),
  93. )
  94. def send_change_email(new_email, current_email, name, link):
  95. send_email(
  96. new_email,
  97. f"Confirm email update on SimpleLogin",
  98. render(
  99. "transactional/change-email.txt",
  100. name=name,
  101. link=link,
  102. new_email=new_email,
  103. current_email=current_email,
  104. ),
  105. render(
  106. "transactional/change-email.html",
  107. name=name,
  108. link=link,
  109. new_email=new_email,
  110. current_email=current_email,
  111. ),
  112. )
  113. def send_new_app_email(email, name):
  114. send_email(
  115. email,
  116. f"Any question/feedback for SimpleLogin {name}?",
  117. render("com/new-app.txt", name=name),
  118. render("com/new-app.html", name=name),
  119. )
  120. def send_test_email_alias(email, name):
  121. send_email(
  122. email,
  123. f"This email is sent to {email}",
  124. render("transactional/test-email.txt", name=name, alias=email),
  125. render("transactional/test-email.html", name=name, alias=email),
  126. )
  127. def send_cannot_create_directory_alias(user, alias, directory):
  128. """when user cancels their subscription, they cannot create alias on the fly.
  129. If this happens, send them an email to notify
  130. """
  131. send_email(
  132. user.email,
  133. f"Alias {alias} cannot be created",
  134. render(
  135. "transactional/cannot-create-alias-directory.txt",
  136. name=user.name,
  137. alias=alias,
  138. directory=directory,
  139. ),
  140. render(
  141. "transactional/cannot-create-alias-directory.html",
  142. name=user.name,
  143. alias=alias,
  144. directory=directory,
  145. ),
  146. )
  147. def send_cannot_create_domain_alias(user, alias, domain):
  148. """when user cancels their subscription, they cannot create alias on the fly with custom domain.
  149. If this happens, send them an email to notify
  150. """
  151. send_email(
  152. user.email,
  153. f"Alias {alias} cannot be created",
  154. render(
  155. "transactional/cannot-create-alias-domain.txt",
  156. name=user.name,
  157. alias=alias,
  158. domain=domain,
  159. ),
  160. render(
  161. "transactional/cannot-create-alias-domain.html",
  162. name=user.name,
  163. alias=alias,
  164. domain=domain,
  165. ),
  166. )
  167. def send_email(to_email, subject, plaintext, html=None):
  168. if NOT_SEND_EMAIL:
  169. LOG.d(
  170. "send email with subject %s to %s, plaintext: %s",
  171. subject,
  172. to_email,
  173. plaintext,
  174. )
  175. return
  176. LOG.d("send email to %s, subject %s", to_email, subject)
  177. if POSTFIX_SUBMISSION_TLS:
  178. smtp = SMTP(POSTFIX_SERVER, 587)
  179. smtp.starttls()
  180. else:
  181. smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25)
  182. msg = MIMEMultipart("alternative")
  183. msg.attach(MIMEText(plaintext, "text"))
  184. if not html:
  185. html = plaintext.replace("\n", "<br>")
  186. msg.attach(MIMEText(html, "html"))
  187. msg["Subject"] = subject
  188. msg["From"] = f"{SUPPORT_NAME} <{SUPPORT_EMAIL}>"
  189. msg["To"] = to_email
  190. msg_id_header = make_msgid()
  191. msg["Message-ID"] = msg_id_header
  192. date_header = formatdate()
  193. msg["Date"] = date_header
  194. # add DKIM
  195. email_domain = SUPPORT_EMAIL[SUPPORT_EMAIL.find("@") + 1 :]
  196. add_dkim_signature(msg, email_domain)
  197. msg_raw = msg.as_bytes()
  198. if SENDER:
  199. smtp.sendmail(SENDER, to_email, msg_raw)
  200. else:
  201. smtp.sendmail(SUPPORT_EMAIL, to_email, msg_raw)
  202. def send_email_with_rate_control(
  203. user: User,
  204. alert_type: str,
  205. to_email: str,
  206. subject,
  207. plaintext,
  208. html=None,
  209. max_alert_24h=MAX_ALERT_24H,
  210. ) -> bool:
  211. """Same as send_email with rate control over alert_type.
  212. For now no more than _MAX_ALERT_24h alert can be sent in the last 24h
  213. Return true if the email is sent, otherwise False
  214. """
  215. to_email = to_email.lower().strip()
  216. one_day_ago = arrow.now().shift(days=-1)
  217. nb_alert = (
  218. SentAlert.query.filter_by(alert_type=alert_type, to_email=to_email)
  219. .filter(SentAlert.created_at > one_day_ago)
  220. .count()
  221. )
  222. if nb_alert >= max_alert_24h:
  223. LOG.warning(
  224. "%s emails were sent to %s in the last 24h, alert type %s",
  225. nb_alert,
  226. to_email,
  227. alert_type,
  228. )
  229. return False
  230. SentAlert.create(user_id=user.id, alert_type=alert_type, to_email=to_email)
  231. db.session.commit()
  232. send_email(to_email, subject, plaintext, html)
  233. return True
  234. def get_email_local_part(address):
  235. """
  236. Get the local part from email
  237. ab@cd.com -> ab
  238. """
  239. return address[: address.find("@")]
  240. def get_email_domain_part(address):
  241. """
  242. Get the domain part from email
  243. ab@cd.com -> cd.com
  244. """
  245. return address[address.find("@") + 1 :].strip().lower()
  246. def add_dkim_signature(msg: Message, email_domain: str):
  247. delete_header(msg, "DKIM-Signature")
  248. # Specify headers in "byte" form
  249. # Generate message signature
  250. sig = dkim.sign(
  251. msg.as_bytes(),
  252. DKIM_SELECTOR,
  253. email_domain.encode(),
  254. DKIM_PRIVATE_KEY.encode(),
  255. include_headers=DKIM_HEADERS,
  256. )
  257. sig = sig.decode()
  258. # remove linebreaks from sig
  259. sig = sig.replace("\n", " ").replace("\r", "")
  260. msg["DKIM-Signature"] = sig[len("DKIM-Signature: ") :]
  261. def add_or_replace_header(msg: Message, header: str, value: str):
  262. """
  263. Remove all occurrences of `header` and add `header` with `value`.
  264. """
  265. delete_header(msg, header)
  266. msg[header] = value
  267. def delete_header(msg: Message, header: str):
  268. """a header can appear several times in message."""
  269. # inspired from https://stackoverflow.com/a/47903323/1428034
  270. for i in reversed(range(len(msg._headers))):
  271. header_name = msg._headers[i][0].lower()
  272. if header_name == header.lower():
  273. del msg._headers[i]
  274. def delete_all_headers_except(msg: Message, headers: [str]):
  275. headers = [h.lower() for h in headers]
  276. for i in reversed(range(len(msg._headers))):
  277. header_name = msg._headers[i][0].lower()
  278. if header_name not in headers:
  279. del msg._headers[i]
  280. def email_belongs_to_alias_domains(address: str) -> bool:
  281. """return True if an email ends with one of the alias domains provided by SimpleLogin"""
  282. for domain in ALIAS_DOMAINS:
  283. if address.endswith("@" + domain):
  284. return True
  285. return False
  286. def email_domain_can_be_used_as_mailbox(email: str) -> bool:
  287. """return True if an email can be used as a personal email. An email domain can be used if it is not
  288. - one of ALIAS_DOMAINS
  289. - one of custom domains
  290. - disposable domain
  291. """
  292. domain = get_email_domain_part(email)
  293. if not domain:
  294. return False
  295. if domain in ALIAS_DOMAINS:
  296. return False
  297. from app.models import CustomDomain
  298. if CustomDomain.get_by(domain=domain, verified=True):
  299. LOG.d("domain %s is a SimpleLogin custom domain", domain)
  300. return False
  301. if is_disposable_domain(domain):
  302. LOG.d("Domain %s is disposable", domain)
  303. return False
  304. # check if email MX domain is disposable
  305. mx_domains = get_mx_domain_list(domain)
  306. # if no MX record, email is not valid
  307. if not mx_domains:
  308. LOG.d("No MX record for domain %s", domain)
  309. return False
  310. for mx_domain in mx_domains:
  311. if is_disposable_domain(mx_domain):
  312. LOG.d("MX Domain %s %s is disposable", mx_domain, domain)
  313. return False
  314. return True
  315. def is_disposable_domain(domain):
  316. for d in DISPOSABLE_EMAIL_DOMAINS:
  317. if domain == d:
  318. return True
  319. # subdomain
  320. if domain.endswith("." + d):
  321. return True
  322. return False
  323. def get_mx_domain_list(domain) -> [str]:
  324. """return list of MX domains for a given email.
  325. domain name ends *without* a dot (".") at the end.
  326. """
  327. priority_domains = get_mx_domains(domain)
  328. return [d[:-1] for _, d in priority_domains]
  329. def personal_email_already_used(email: str) -> bool:
  330. """test if an email can be used as user email
  331. """
  332. if User.get_by(email=email):
  333. return True
  334. return False
  335. def mailbox_already_used(email: str, user) -> bool:
  336. if Mailbox.get_by(email=email, user_id=user.id):
  337. return True
  338. # support the case user wants to re-add their real email as mailbox
  339. # can happen when user changes their root email and wants to add this new email as mailbox
  340. if email == user.email:
  341. return False
  342. return False
  343. def get_orig_message_from_bounce(msg: Message) -> Message:
  344. """parse the original email from Bounce"""
  345. i = 0
  346. for part in msg.walk():
  347. i += 1
  348. # the original message is the 4th part
  349. # 1st part is the root part, multipart/report
  350. # 2nd is text/plain, Postfix log
  351. # ...
  352. # 7th is original message
  353. if i == 7:
  354. return part
  355. def get_header_from_bounce(msg: Message, header: str) -> str:
  356. """using regex to get header value from bounce message
  357. get_orig_message_from_bounce is better. This should be the last option
  358. """
  359. msg_str = str(msg)
  360. exp = re.compile(f"{header}.*\n")
  361. r = re.search(exp, msg_str)
  362. if r:
  363. # substr should be something like 'HEADER: 1234'
  364. substr = msg_str[r.start() : r.end()].strip()
  365. parts = substr.split(":")
  366. return parts[1].strip()
  367. return None
  368. def get_orig_message_from_spamassassin_report(msg: Message) -> Message:
  369. """parse the original email from Spamassassin report"""
  370. i = 0
  371. for part in msg.walk():
  372. i += 1
  373. # the original message is the 4th part
  374. # 1st part is the root part, multipart/report
  375. # 2nd is text/plain, SpamAssassin part
  376. # 3rd is the original message in message/rfc822 content type
  377. # 4th is original message
  378. if i == 4:
  379. return part
  380. def get_addrs_from_header(msg: Message, header) -> [str]:
  381. """Get all addresses contained in `header`
  382. Used for To or CC header.
  383. """
  384. ret = []
  385. header_content = msg.get_all(header)
  386. if not header_content:
  387. return ret
  388. for addrs in header_content:
  389. # force convert header to string, sometimes addrs is Header object
  390. addrs = str(addrs)
  391. for addr in addrs.split(","):
  392. ret.append(addr.strip())
  393. # do not return empty string
  394. return [r for r in ret if r]
  395. def get_spam_info(msg: Message, max_score=None) -> (bool, str):
  396. """parse SpamAssassin header to detect whether a message is classified as spam.
  397. Return (is spam, spam status detail)
  398. The header format is
  399. ```X-Spam-Status: No, score=-0.1 required=5.0 tests=DKIM_SIGNED,DKIM_VALID,
  400. DKIM_VALID_AU,RCVD_IN_DNSWL_BLOCKED,RCVD_IN_MSPIKE_H2,SPF_PASS,
  401. URIBL_BLOCKED autolearn=unavailable autolearn_force=no version=3.4.2```
  402. """
  403. spamassassin_status = msg["X-Spam-Status"]
  404. if not spamassassin_status:
  405. return False, ""
  406. return get_spam_from_header(spamassassin_status, max_score=max_score)
  407. def get_spam_from_header(spam_status_header, max_score=None) -> (bool, str):
  408. """get spam info from X-Spam-Status header
  409. Return (is spam, spam status detail).
  410. The spam_status_header has the following format
  411. ```No, score=-0.1 required=5.0 tests=DKIM_SIGNED,DKIM_VALID,
  412. DKIM_VALID_AU,RCVD_IN_DNSWL_BLOCKED,RCVD_IN_MSPIKE_H2,SPF_PASS,
  413. URIBL_BLOCKED autolearn=unavailable autolearn_force=no version=3.4.2```
  414. """
  415. # yes or no
  416. spamassassin_answer = spam_status_header[: spam_status_header.find(",")]
  417. if max_score:
  418. # spam score
  419. # get the score section "score=-0.1"
  420. score_section = (
  421. spam_status_header[spam_status_header.find(",") + 1 :].strip().split(" ")[0]
  422. )
  423. score = float(score_section[len("score=") :])
  424. if score >= max_score:
  425. LOG.warning("Spam score %s exceeds %s", score, max_score)
  426. return True, spam_status_header
  427. return spamassassin_answer.lower() == "yes", spam_status_header
  428. def parseaddr_unicode(addr) -> (str, str):
  429. """Like parseaddr but return name in unicode instead of in RFC 2047 format
  430. '=?UTF-8?B?TmjGoW4gTmd1eeG7hW4=?= <abcd@gmail.com>' -> ('Nhơn Nguyễn', "abcd@gmail.com")
  431. """
  432. name, email = parseaddr(addr)
  433. email = email.strip().lower()
  434. if name:
  435. name = name.strip()
  436. decoded_string, charset = decode_header(name)[0]
  437. if charset is not None:
  438. try:
  439. name = decoded_string.decode(charset)
  440. except UnicodeDecodeError:
  441. LOG.warning("Cannot decode addr name %s", name)
  442. name = ""
  443. else:
  444. name = decoded_string
  445. return name, email
  446. def copy(msg: Message) -> Message:
  447. """return a copy of message"""
  448. return email.message_from_bytes(msg.as_bytes())
  449. def to_bytes(msg: Message):
  450. """replace Message.as_bytes() method by trying different policies"""
  451. try:
  452. return msg.as_bytes()
  453. except UnicodeEncodeError:
  454. LOG.warning("as_bytes fails with default policy, try SMTP policy")
  455. try:
  456. return msg.as_bytes(policy=email.policy.SMTP)
  457. except UnicodeEncodeError:
  458. LOG.warning("as_bytes fails with SMTP policy, try SMTPUTF8 policy")
  459. return msg.as_bytes(policy=email.policy.SMTPUTF8)