email_handler.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 aiosmtpd.controller import Controller
  33. from app.config import EMAIL_DOMAIN, POSTFIX_SERVER, URL
  34. from app.email_utils import (
  35. get_email_name,
  36. get_email_part,
  37. send_email,
  38. add_dkim_signature,
  39. get_email_domain_part,
  40. add_or_replace_header,
  41. delete_header,
  42. )
  43. from app.extensions import db
  44. from app.log import LOG
  45. from app.models import GenEmail, ForwardEmail, ForwardEmailLog, CustomDomain, Directory
  46. from app.utils import random_string
  47. from server import create_app
  48. # fix the database connection leak issue
  49. # use this method instead of create_app
  50. def new_app():
  51. app = create_app()
  52. @app.teardown_appcontext
  53. def shutdown_session(response_or_exc):
  54. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  55. db.session.remove()
  56. # dispose the engine too
  57. db.engine.dispose()
  58. return app
  59. class MailHandler:
  60. async def handle_DATA(self, server, session, envelope):
  61. LOG.debug(">>> New message <<<")
  62. LOG.debug("Mail from %s", envelope.mail_from)
  63. LOG.debug("Rcpt to %s", envelope.rcpt_tos)
  64. message_data = envelope.content.decode("utf8", errors="replace")
  65. # Only when debug
  66. # LOG.debug("Message data:\n")
  67. # LOG.debug(message_data)
  68. # host IP, setup via Docker network
  69. smtp = SMTP(POSTFIX_SERVER, 25)
  70. msg = Parser(policy=SMTPUTF8).parsestr(message_data)
  71. rcpt_to = envelope.rcpt_tos[0].lower()
  72. # Reply case
  73. # reply+ or ra+ (reverse-alias) prefix
  74. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  75. LOG.debug("Reply phase")
  76. app = new_app()
  77. with app.app_context():
  78. return self.handle_reply(envelope, smtp, msg)
  79. else: # Forward case
  80. LOG.debug("Forward phase")
  81. app = new_app()
  82. with app.app_context():
  83. return self.handle_forward(envelope, smtp, msg)
  84. def handle_forward(self, envelope, smtp: SMTP, msg: Message) -> str:
  85. """return *status_code message*"""
  86. alias = envelope.rcpt_tos[0].lower() # alias@SL
  87. gen_email = GenEmail.get_by(email=alias)
  88. if not gen_email:
  89. LOG.d("alias %s not exist. Try to see if it can created on the fly", alias)
  90. # try to see if alias could be created on-the-fly
  91. on_the_fly = False
  92. # check if alias belongs to a directory, ie having directory/anything@EMAIL_DOMAIN format
  93. if alias.endswith(EMAIL_DOMAIN):
  94. if "/" in alias:
  95. directory_name = alias[: alias.find("/")]
  96. LOG.d("directory_name %s", directory_name)
  97. directory = Directory.get_by(name=directory_name)
  98. if directory:
  99. LOG.d("create alias %s for directory %s", alias, directory)
  100. on_the_fly = True
  101. gen_email = GenEmail.create(
  102. email=alias,
  103. user_id=directory.user_id,
  104. directory_id=directory.id,
  105. )
  106. db.session.commit()
  107. else:
  108. # check if alias is custom-domain alias and if the custom-domain has catch-all enabled
  109. alias_domain = get_email_domain_part(alias)
  110. custom_domain = CustomDomain.get_by(domain=alias_domain)
  111. if custom_domain and custom_domain.catch_all:
  112. LOG.d("create alias %s for domain %s", alias, custom_domain)
  113. on_the_fly = True
  114. gen_email = GenEmail.create(
  115. email=alias,
  116. user_id=custom_domain.user_id,
  117. custom_domain_id=custom_domain.id,
  118. automatic_creation=True,
  119. )
  120. db.session.commit()
  121. if not on_the_fly:
  122. LOG.d("alias %s not exist, return 510", alias)
  123. return "510 Email not exist"
  124. user_email = gen_email.user.email
  125. website_email = get_email_part(msg["From"])
  126. forward_email = ForwardEmail.get_by(
  127. gen_email_id=gen_email.id, website_email=website_email
  128. )
  129. if not forward_email:
  130. LOG.debug(
  131. "create forward email for alias %s and website email %s",
  132. alias,
  133. website_email,
  134. )
  135. # generate a reply_email, make sure it is unique
  136. # not use while to avoid infinite loop
  137. for _ in range(1000):
  138. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  139. if not ForwardEmail.get_by(reply_email=reply_email):
  140. break
  141. forward_email = ForwardEmail.create(
  142. gen_email_id=gen_email.id,
  143. website_email=website_email,
  144. website_from=msg["From"],
  145. reply_email=reply_email,
  146. )
  147. db.session.commit()
  148. forward_log = ForwardEmailLog.create(forward_id=forward_email.id)
  149. if gen_email.enabled:
  150. # add custom header
  151. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  152. # remove reply-to header if present
  153. delete_header(msg, "Reply-To")
  154. # change the from header so the sender comes from @SL
  155. # so it can pass DMARC check
  156. # replace the email part in from: header
  157. from_header = (
  158. get_email_name(msg["From"])
  159. + " - "
  160. + website_email.replace("@", " at ")
  161. + f" <{forward_email.reply_email}>"
  162. )
  163. msg.replace_header("From", from_header)
  164. LOG.d("new from header:%s", from_header)
  165. # add List-Unsubscribe header
  166. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{gen_email.id}"
  167. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  168. add_or_replace_header(
  169. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  170. )
  171. add_dkim_signature(msg, EMAIL_DOMAIN)
  172. LOG.d(
  173. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  174. website_email,
  175. user_email,
  176. envelope.mail_options,
  177. envelope.rcpt_options,
  178. )
  179. # smtp.send_message has UnicodeEncodeErroremail issue
  180. # encode message raw directly instead
  181. msg_raw = msg.as_string().encode()
  182. smtp.sendmail(
  183. forward_email.reply_email,
  184. user_email,
  185. msg_raw,
  186. envelope.mail_options,
  187. envelope.rcpt_options,
  188. )
  189. else:
  190. LOG.d("%s is disabled, do not forward", gen_email)
  191. forward_log.blocked = True
  192. db.session.commit()
  193. return "250 Message accepted for delivery"
  194. def handle_reply(self, envelope, smtp: SMTP, msg: Message) -> str:
  195. reply_email = envelope.rcpt_tos[0].lower()
  196. # reply_email must end with EMAIL_DOMAIN
  197. if not reply_email.endswith(EMAIL_DOMAIN):
  198. LOG.error(f"Reply email {reply_email} has wrong domain")
  199. return "550 wrong reply email"
  200. forward_email = ForwardEmail.get_by(reply_email=reply_email)
  201. alias: str = forward_email.gen_email.email
  202. # alias must end with EMAIL_DOMAIN or custom-domain
  203. alias_domain = alias[alias.find("@") + 1 :]
  204. if alias_domain != EMAIL_DOMAIN:
  205. if not CustomDomain.get_by(domain=alias_domain):
  206. return "550 alias unknown by SimpleLogin"
  207. user_email = forward_email.gen_email.user.email
  208. if envelope.mail_from.lower() != user_email.lower():
  209. LOG.error(
  210. f"Reply email can only be used by user email. Actual mail_from: %s. User email %s. reply_email %s",
  211. envelope.mail_from,
  212. user_email,
  213. reply_email,
  214. )
  215. send_email(
  216. envelope.mail_from,
  217. f"Your email ({envelope.mail_from}) is not allowed to send email to {reply_email}",
  218. "",
  219. "",
  220. )
  221. return "550 ignored"
  222. delete_header(msg, "DKIM-Signature")
  223. # the email comes from alias
  224. msg.replace_header("From", alias)
  225. # some email providers like ProtonMail adds automatically the Reply-To field
  226. # make sure to delete it
  227. delete_header(msg, "Reply-To")
  228. msg.replace_header("To", forward_email.website_email)
  229. # add List-Unsubscribe header
  230. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{forward_email.gen_email_id}"
  231. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  232. add_or_replace_header(
  233. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  234. )
  235. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  236. delete_header(msg, "Received-SPF")
  237. LOG.d(
  238. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  239. alias,
  240. forward_email.website_email,
  241. envelope.mail_options,
  242. envelope.rcpt_options,
  243. )
  244. if alias_domain == EMAIL_DOMAIN:
  245. add_dkim_signature(msg, EMAIL_DOMAIN)
  246. # add DKIM-Signature for non-custom-domain alias
  247. else:
  248. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  249. if custom_domain.dkim_verified:
  250. add_dkim_signature(msg, alias_domain)
  251. msg_raw = msg.as_string().encode()
  252. smtp.sendmail(
  253. alias,
  254. forward_email.website_email,
  255. msg_raw,
  256. envelope.mail_options,
  257. envelope.rcpt_options,
  258. )
  259. ForwardEmailLog.create(forward_id=forward_email.id, is_reply=True)
  260. db.session.commit()
  261. return "250 Message accepted for delivery"
  262. if __name__ == "__main__":
  263. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  264. controller.start()
  265. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  266. while True:
  267. time.sleep(2)