email_handler.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 EmailMessage
  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.extensions import db
  35. from app.log import LOG
  36. from app.models import GenEmail, ForwardEmail, ForwardEmailLog
  37. from app.utils import random_words
  38. from server import create_app
  39. # fix the database connection leak issue
  40. # use this method instead of create_app
  41. def new_app():
  42. app = create_app()
  43. @app.teardown_appcontext
  44. def shutdown_session(response_or_exc):
  45. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  46. db.session.remove()
  47. # dispose the engine too
  48. db.engine.dispose()
  49. return app
  50. class MailHandler:
  51. async def handle_DATA(self, server, session, envelope):
  52. LOG.debug(">>> New message <<<")
  53. LOG.debug("Mail from %s", envelope.mail_from)
  54. LOG.debug("Rcpt to %s", envelope.rcpt_tos)
  55. message_data = envelope.content.decode("utf8", errors="replace")
  56. # Only when debug
  57. # LOG.debug("Message data:\n")
  58. # LOG.debug(message_data)
  59. # host IP, setup via Docker network
  60. smtp = SMTP(POSTFIX_SERVER, 25)
  61. msg = Parser(policy=SMTPUTF8).parsestr(message_data)
  62. if not envelope.rcpt_tos[0].startswith("reply+"): # Forward case
  63. LOG.debug("Forward phase")
  64. app = new_app()
  65. with app.app_context():
  66. return self.handle_forward(envelope, smtp, msg)
  67. else:
  68. LOG.debug("Reply phase")
  69. app = new_app()
  70. with app.app_context():
  71. return self.handle_reply(envelope, smtp, msg)
  72. def handle_forward(self, envelope, smtp, msg: EmailMessage) -> str:
  73. """return *status_code message*"""
  74. alias = envelope.rcpt_tos[0] # alias@SL
  75. gen_email = GenEmail.get_by(email=alias)
  76. if not gen_email:
  77. LOG.d("alias %s not exist")
  78. return "510 Email not exist"
  79. user_email = gen_email.user.email
  80. website_email = get_email_part(msg["From"])
  81. forward_email = ForwardEmail.get_by(
  82. gen_email_id=gen_email.id, website_email=website_email
  83. )
  84. if not forward_email:
  85. LOG.debug(
  86. "create forward email for alias %s and website email %s",
  87. alias,
  88. website_email,
  89. )
  90. # todo: make sure reply_email is unique
  91. reply_email = f"reply+{random_words()}@{EMAIL_DOMAIN}"
  92. forward_email = ForwardEmail.create(
  93. gen_email_id=gen_email.id,
  94. website_email=website_email,
  95. website_from=msg["From"],
  96. reply_email=reply_email,
  97. )
  98. db.session.commit()
  99. forward_log = ForwardEmailLog.create(forward_id=forward_email.id)
  100. if gen_email.enabled:
  101. # add custom header
  102. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  103. # remove reply-to header if present
  104. if msg["Reply-To"]:
  105. LOG.d("Delete reply-to header %s", msg["Reply-To"])
  106. del msg["Reply-To"]
  107. # change the from header so the sender comes from @SL
  108. # so it can pass DMARC check
  109. # replace the email part in from: header
  110. from_header = (
  111. get_email_name(msg["From"])
  112. + " - "
  113. + website_email.replace("@", " at ")
  114. + f" <{forward_email.reply_email}>"
  115. )
  116. msg.replace_header("From", from_header)
  117. LOG.d("new from header:%s", from_header)
  118. # add List-Unsubscribe header
  119. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{gen_email.id}"
  120. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  121. add_or_replace_header(
  122. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  123. )
  124. # remove DKIM-Signature as Postfix will add this header
  125. if msg["DKIM-Signature"]:
  126. LOG.d("Remove DKIM-Signature %s", msg["DKIM-Signature"])
  127. del msg["DKIM-Signature"]
  128. original_subject = msg["Subject"]
  129. LOG.d(
  130. "Forward mail from %s to %s, subject %s, mail_options %s, rcpt_options %s ",
  131. website_email,
  132. user_email,
  133. original_subject,
  134. envelope.mail_options,
  135. envelope.rcpt_options,
  136. )
  137. # smtp.send_message has UnicodeEncodeErroremail issue
  138. # encode message raw directly instead
  139. msg_raw = msg.as_string().encode()
  140. smtp.sendmail(
  141. forward_email.reply_email,
  142. user_email,
  143. msg_raw,
  144. envelope.mail_options,
  145. envelope.rcpt_options,
  146. )
  147. # smtp.send_message(
  148. # msg,
  149. # from_addr=forward_email.reply_email,
  150. # to_addrs=[user_email], # user personal email
  151. # mail_options=envelope.mail_options,
  152. # rcpt_options=envelope.rcpt_options,
  153. # )
  154. else:
  155. LOG.d("%s is disabled, do not forward", gen_email)
  156. forward_log.blocked = True
  157. db.session.commit()
  158. return "250 Message accepted for delivery"
  159. def handle_reply(self, envelope, smtp, msg: EmailMessage) -> str:
  160. reply_email = envelope.rcpt_tos[0]
  161. # reply_email must end with EMAIL_DOMAIN
  162. if not reply_email.endswith(EMAIL_DOMAIN):
  163. LOG.error(f"Reply email {reply_email} has wrong domain")
  164. return "550 wrong reply email"
  165. forward_email = ForwardEmail.get_by(reply_email=reply_email)
  166. alias: str = forward_email.gen_email.email
  167. # todo: add DKIM-Signature for custom domain
  168. # remove DKIM-Signature for custom domain
  169. if not alias.endswith(EMAIL_DOMAIN) and msg["DKIM-Signature"]:
  170. LOG.d(
  171. "Remove DKIM-Signature %s for custom-domain alias %s",
  172. msg["DKIM-Signature"],
  173. alias,
  174. )
  175. del msg["DKIM-Signature"]
  176. # email seems to come from alias
  177. msg.replace_header("From", alias)
  178. msg.replace_header("To", forward_email.website_email)
  179. # add List-Unsubscribe header
  180. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{forward_email.gen_email_id}"
  181. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  182. add_or_replace_header(
  183. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  184. )
  185. LOG.d(
  186. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  187. alias,
  188. forward_email.website_email,
  189. envelope.mail_options,
  190. envelope.rcpt_options,
  191. )
  192. msg_raw = msg.as_string().encode()
  193. smtp.sendmail(
  194. alias,
  195. forward_email.website_email,
  196. msg_raw,
  197. envelope.mail_options,
  198. envelope.rcpt_options,
  199. )
  200. ForwardEmailLog.create(forward_id=forward_email.id, is_reply=True)
  201. db.session.commit()
  202. return "250 Message accepted for delivery"
  203. def add_or_replace_header(msg: EmailMessage, header: str, value: str):
  204. try:
  205. msg.add_header(header, value)
  206. except ValueError:
  207. # the header exists already
  208. msg.replace_header(header, value)
  209. def get_email_name(email_from):
  210. """parse email from header and return the name part
  211. First Last <ab@cd.com> -> First Last
  212. ab@cd.com -> ""
  213. """
  214. if "<" in email_from:
  215. return email_from[: email_from.find("<")].strip()
  216. return ""
  217. def get_email_part(email_from):
  218. """parse email from header and return the email part
  219. First Last <ab@cd.com> -> ab@cd.com
  220. ab@cd.com -> ""
  221. """
  222. if "<" in email_from:
  223. return email_from[email_from.find("<") + 1 : email_from.find(">")].strip()
  224. return email_from
  225. if __name__ == "__main__":
  226. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  227. controller.start()
  228. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  229. while True:
  230. time.sleep(2)