email_utils.py 12 KB

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