email_handler.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. """
  2. Handle the email *forward* and *reply*. phase. There are 3 actors:
  3. - website: who sends emails to alias@sl.co address
  4. - SL email handler (this script)
  5. - user personal email: to be protected. Should never leak to website.
  6. This script makes sure that in the forward phase, the email that is forwarded to user personal email has the following
  7. envelope and header fields:
  8. Envelope:
  9. mail from: @website
  10. rcpt to: @personal_email
  11. Header:
  12. From: @website
  13. To: alias@sl.co # so user knows this email is sent to alias
  14. Reply-to: special@sl.co # magic HERE
  15. And in the reply phase:
  16. Envelope:
  17. mail from: @website
  18. rcpt to: @website
  19. Header:
  20. From: alias@sl.co # so for website the email comes from alias. magic HERE
  21. To: @website
  22. The special@sl.co allows to hide user personal email when user clicks "Reply" to the forwarded email.
  23. It should contain the following info:
  24. - alias
  25. - @website
  26. """
  27. import time
  28. from email.message import Message
  29. from email.parser import Parser
  30. from email.policy import SMTPUTF8
  31. from smtplib import SMTP
  32. from typing import Optional
  33. from aiosmtpd.controller import Controller
  34. from app.config import (
  35. EMAIL_DOMAIN,
  36. POSTFIX_SERVER,
  37. URL,
  38. ALIAS_DOMAINS,
  39. ADMIN_EMAIL,
  40. SUPPORT_EMAIL,
  41. )
  42. from app.email_utils import (
  43. get_email_name,
  44. get_email_part,
  45. send_email,
  46. add_dkim_signature,
  47. get_email_domain_part,
  48. add_or_replace_header,
  49. delete_header,
  50. send_cannot_create_directory_alias,
  51. send_cannot_create_domain_alias,
  52. email_belongs_to_alias_domains,
  53. render,
  54. )
  55. from app.extensions import db
  56. from app.log import LOG
  57. from app.models import (
  58. GenEmail,
  59. ForwardEmail,
  60. ForwardEmailLog,
  61. CustomDomain,
  62. Directory,
  63. User,
  64. DeletedAlias,
  65. )
  66. from app.utils import random_string
  67. from server import create_app
  68. # fix the database connection leak issue
  69. # use this method instead of create_app
  70. def new_app():
  71. app = create_app()
  72. @app.teardown_appcontext
  73. def shutdown_session(response_or_exc):
  74. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  75. db.session.remove()
  76. # dispose the engine too
  77. db.engine.dispose()
  78. return app
  79. def try_auto_create(alias: str) -> Optional[GenEmail]:
  80. """Try to auto-create the alias using directory or catch-all domain
  81. """
  82. # check if alias belongs to a directory, ie having directory/anything@EMAIL_DOMAIN format
  83. if email_belongs_to_alias_domains(alias):
  84. # if there's no directory separator in the alias, no way to auto-create it
  85. if "/" not in alias and "+" not in alias and "#" not in alias:
  86. return None
  87. # alias contains one of the 3 special directory separator: "/", "+" or "#"
  88. if "/" in alias:
  89. sep = "/"
  90. elif "+" in alias:
  91. sep = "+"
  92. else:
  93. sep = "#"
  94. directory_name = alias[: alias.find(sep)]
  95. LOG.d("directory_name %s", directory_name)
  96. directory = Directory.get_by(name=directory_name)
  97. if not directory:
  98. return None
  99. dir_user: User = directory.user
  100. if not dir_user.can_create_new_alias():
  101. send_cannot_create_directory_alias(dir_user, alias, directory_name)
  102. return None
  103. # if alias has been deleted before, do not auto-create it
  104. if DeletedAlias.get_by(email=alias, user_id=directory.user_id):
  105. LOG.error(
  106. "Alias %s was deleted before, cannot auto-create using directory %s, user %s",
  107. alias,
  108. directory_name,
  109. dir_user,
  110. )
  111. return None
  112. LOG.d("create alias %s for directory %s", alias, directory)
  113. gen_email = GenEmail.create(
  114. email=alias, user_id=directory.user_id, directory_id=directory.id,
  115. )
  116. db.session.commit()
  117. return gen_email
  118. # try to create alias on-the-fly with custom-domain catch-all feature
  119. # check if alias is custom-domain alias and if the custom-domain has catch-all enabled
  120. alias_domain = get_email_domain_part(alias)
  121. custom_domain = CustomDomain.get_by(domain=alias_domain)
  122. if not custom_domain or custom_domain.catch_all:
  123. return None
  124. # custom_domain has catch-all enabled
  125. domain_user: User = custom_domain.user
  126. if not domain_user.can_create_new_alias():
  127. send_cannot_create_domain_alias(domain_user, alias, alias_domain)
  128. return None
  129. # if alias has been deleted before, do not auto-create it
  130. if DeletedAlias.get_by(email=alias, user_id=custom_domain.user_id):
  131. LOG.error(
  132. "Alias %s was deleted before, cannot auto-create using domain catch-all %s, user %s",
  133. alias,
  134. custom_domain,
  135. domain_user,
  136. )
  137. return None
  138. LOG.d("create alias %s for domain %s", alias, custom_domain)
  139. gen_email = GenEmail.create(
  140. email=alias,
  141. user_id=custom_domain.user_id,
  142. custom_domain_id=custom_domain.id,
  143. automatic_creation=True,
  144. )
  145. db.session.commit()
  146. return gen_email
  147. def get_or_create_forward_email(
  148. website_from_header: str, gen_email: GenEmail
  149. ) -> ForwardEmail:
  150. """
  151. website_from_header can be the full-form email, i.e. "First Last <email@example.com>"
  152. """
  153. website_email = get_email_part(website_from_header)
  154. forward_email = ForwardEmail.get_by(
  155. gen_email_id=gen_email.id, website_email=website_email
  156. )
  157. if forward_email:
  158. # update the website_from if needed
  159. if forward_email.website_from != website_from_header:
  160. LOG.d("Update From header for %s", forward_email)
  161. forward_email.website_from = website_from_header
  162. db.session.commit()
  163. else:
  164. LOG.debug(
  165. "create forward email for alias %s and website email %s",
  166. gen_email,
  167. website_from_header,
  168. )
  169. # generate a reply_email, make sure it is unique
  170. # not use while loop to avoid infinite loop
  171. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  172. for _ in range(1000):
  173. if not ForwardEmail.get_by(reply_email=reply_email):
  174. # found!
  175. break
  176. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  177. forward_email = ForwardEmail.create(
  178. gen_email_id=gen_email.id,
  179. website_email=website_email,
  180. website_from=website_from_header,
  181. reply_email=reply_email,
  182. )
  183. db.session.commit()
  184. return forward_email
  185. def handle_forward(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> str:
  186. """return *status_code message*"""
  187. alias = rcpt_to.lower() # alias@SL
  188. gen_email = GenEmail.get_by(email=alias)
  189. if not gen_email:
  190. LOG.d("alias %s not exist. Try to see if it can be created on the fly", alias)
  191. gen_email = try_auto_create(alias)
  192. if not gen_email:
  193. LOG.d("alias %s cannot be created on-the-fly, return 510", alias)
  194. return "510 Email not exist"
  195. if gen_email.mailbox_id:
  196. mailbox_email = gen_email.mailbox.email
  197. else:
  198. mailbox_email = gen_email.user.email
  199. forward_email = get_or_create_forward_email(msg["From"], gen_email)
  200. forward_log = ForwardEmailLog.create(forward_id=forward_email.id)
  201. if gen_email.enabled:
  202. # add custom header
  203. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  204. # remove reply-to header if present
  205. delete_header(msg, "Reply-To")
  206. # change the from header so the sender comes from @SL
  207. # so it can pass DMARC check
  208. # replace the email part in from: header
  209. website_from_header = msg["From"]
  210. website_email = get_email_part(website_from_header)
  211. from_header = (
  212. get_email_name(website_from_header)
  213. + ("" if get_email_name(website_from_header) == "" else " - ")
  214. + website_email.replace("@", " at ")
  215. + f" <{forward_email.reply_email}>"
  216. )
  217. msg.replace_header("From", from_header)
  218. LOG.d("new from header:%s", from_header)
  219. # add List-Unsubscribe header
  220. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{gen_email.id}"
  221. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  222. add_or_replace_header(
  223. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  224. )
  225. add_dkim_signature(msg, EMAIL_DOMAIN)
  226. LOG.d(
  227. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  228. website_email,
  229. mailbox_email,
  230. envelope.mail_options,
  231. envelope.rcpt_options,
  232. )
  233. # smtp.send_message has UnicodeEncodeErroremail issue
  234. # encode message raw directly instead
  235. msg_raw = msg.as_string().encode()
  236. smtp.sendmail(
  237. forward_email.reply_email,
  238. mailbox_email,
  239. msg_raw,
  240. envelope.mail_options,
  241. envelope.rcpt_options,
  242. )
  243. else:
  244. LOG.d("%s is disabled, do not forward", gen_email)
  245. forward_log.blocked = True
  246. db.session.commit()
  247. return "250 Message accepted for delivery"
  248. def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> str:
  249. reply_email = rcpt_to.lower()
  250. # reply_email must end with EMAIL_DOMAIN
  251. if not reply_email.endswith(EMAIL_DOMAIN):
  252. LOG.warning(f"Reply email {reply_email} has wrong domain")
  253. return "550 wrong reply email"
  254. forward_email = ForwardEmail.get_by(reply_email=reply_email)
  255. if not forward_email:
  256. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  257. return "550 wrong reply email"
  258. alias: str = forward_email.gen_email.email
  259. alias_domain = alias[alias.find("@") + 1 :]
  260. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  261. if not email_belongs_to_alias_domains(alias):
  262. if not CustomDomain.get_by(domain=alias_domain):
  263. return "550 alias unknown by SimpleLogin"
  264. gen_email = forward_email.gen_email
  265. if gen_email.mailbox_id:
  266. mailbox_email = gen_email.mailbox.email
  267. else:
  268. mailbox_email = gen_email.user.email
  269. # bounce email initiated by Postfix
  270. # can happen in case emails cannot be delivered to user-email
  271. # in this case Postfix will try to send a bounce report to original sender, which is
  272. # the "reply email"
  273. if envelope.mail_from == "<>":
  274. LOG.error(
  275. "Bounce when sending to alias %s, user %s, from header: %s",
  276. alias,
  277. gen_email.user,
  278. msg["From"],
  279. )
  280. # send the bounce email payload to admin
  281. msg.replace_header("From", SUPPORT_EMAIL)
  282. msg.replace_header("To", ADMIN_EMAIL)
  283. add_dkim_signature(msg, get_email_domain_part(SUPPORT_EMAIL))
  284. smtp.sendmail(
  285. SUPPORT_EMAIL,
  286. ADMIN_EMAIL,
  287. msg.as_string().encode(),
  288. envelope.mail_options,
  289. envelope.rcpt_options,
  290. )
  291. return "550 ignored"
  292. # only mailbox can send email to the reply-email
  293. if envelope.mail_from.lower() != mailbox_email.lower():
  294. LOG.warning(
  295. f"Reply email can only be used by user email. Actual mail_from: %s. msg from header: %s, User email %s. reply_email %s",
  296. envelope.mail_from,
  297. msg["From"],
  298. mailbox_email,
  299. reply_email,
  300. )
  301. user = gen_email.user
  302. send_email(
  303. mailbox_email,
  304. f"Reply from your alias {alias} only works from your mailbox",
  305. render(
  306. "transactional/reply-must-use-personal-email.txt",
  307. name=user.name,
  308. alias=alias,
  309. sender=envelope.mail_from,
  310. mailbox_email=mailbox_email,
  311. ),
  312. render(
  313. "transactional/reply-must-use-personal-email.html",
  314. name=user.name,
  315. alias=alias,
  316. sender=envelope.mail_from,
  317. mailbox_email=mailbox_email,
  318. ),
  319. )
  320. # Notify sender that they cannot send emails to this address
  321. send_email(
  322. envelope.mail_from,
  323. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  324. render(
  325. "transactional/send-from-alias-from-unknown-sender.txt",
  326. sender=envelope.mail_from,
  327. reply_email=reply_email,
  328. ),
  329. "",
  330. )
  331. return "550 ignored"
  332. delete_header(msg, "DKIM-Signature")
  333. # the email comes from alias
  334. msg.replace_header("From", alias)
  335. # some email providers like ProtonMail adds automatically the Reply-To field
  336. # make sure to delete it
  337. delete_header(msg, "Reply-To")
  338. msg.replace_header("To", forward_email.website_email)
  339. # add List-Unsubscribe header
  340. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{forward_email.gen_email_id}"
  341. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  342. add_or_replace_header(msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click")
  343. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  344. delete_header(msg, "Received-SPF")
  345. LOG.d(
  346. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  347. alias,
  348. forward_email.website_email,
  349. envelope.mail_options,
  350. envelope.rcpt_options,
  351. )
  352. if alias_domain in ALIAS_DOMAINS:
  353. add_dkim_signature(msg, alias_domain)
  354. # add DKIM-Signature for custom-domain alias
  355. else:
  356. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  357. if custom_domain.dkim_verified:
  358. add_dkim_signature(msg, alias_domain)
  359. msg_raw = msg.as_string().encode()
  360. smtp.sendmail(
  361. alias,
  362. forward_email.website_email,
  363. msg_raw,
  364. envelope.mail_options,
  365. envelope.rcpt_options,
  366. )
  367. ForwardEmailLog.create(forward_id=forward_email.id, is_reply=True)
  368. db.session.commit()
  369. return "250 Message accepted for delivery"
  370. class MailHandler:
  371. async def handle_DATA(self, server, session, envelope):
  372. LOG.debug(">>> New message <<<")
  373. LOG.debug("Mail from %s", envelope.mail_from)
  374. LOG.debug("Rcpt to %s", envelope.rcpt_tos)
  375. message_data = envelope.content.decode("utf8", errors="replace")
  376. smtp = SMTP(POSTFIX_SERVER, 25)
  377. msg = Parser(policy=SMTPUTF8).parsestr(message_data)
  378. for rcpt_to in envelope.rcpt_tos:
  379. # Reply case
  380. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  381. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  382. LOG.debug("Reply phase")
  383. app = new_app()
  384. with app.app_context():
  385. return handle_reply(envelope, smtp, msg, rcpt_to)
  386. else: # Forward case
  387. LOG.debug("Forward phase")
  388. app = new_app()
  389. with app.app_context():
  390. return handle_forward(envelope, smtp, msg, rcpt_to)
  391. if __name__ == "__main__":
  392. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  393. controller.start()
  394. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  395. while True:
  396. time.sleep(2)