email_utils.py 14 KB

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