email_utils.py 14 KB

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