email_handler.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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: srs@sl.co # managed by SRS
  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: srs@sl.co # managed by SRS
  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.parser import Parser
  29. from email.policy import default
  30. from smtplib import SMTP
  31. from aiosmtpd.controller import Controller
  32. from app.config import EMAIL_DOMAIN
  33. from app.email_utils import notify_admin
  34. from app.extensions import db
  35. from app.log import LOG
  36. from app.models import GenEmail, ForwardEmail
  37. from app.utils import random_words
  38. from server import create_app
  39. def parse_srs_email(srs) -> str:
  40. """
  41. Parse srs0=8lgw=y6=outlook.com=abcd@mailsl.meo.ovh and return abcd@outlook.com
  42. """
  43. local_part = srs[: srs.find("@")] # srs0=8lgw=y6=outlook.com=abcd
  44. local_email_part = local_part[local_part.rfind("=") + 1 :] # abcd
  45. rest = local_part[: local_part.rfind("=")] # srs0=8lgw=y6=outlook.com
  46. domain_email_part = rest[rest.rfind("=") + 1 :] # outlook.com
  47. return f"{local_email_part}@{domain_email_part}"
  48. class MailHandler:
  49. async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
  50. if not address.endswith(EMAIL_DOMAIN):
  51. LOG.error(f"Not handle email {address}")
  52. return "550 not relaying to that domain"
  53. envelope.rcpt_tos.append(address)
  54. return "250 OK"
  55. async def handle_DATA(self, server, session, envelope):
  56. LOG.debug(">>> New message <<<")
  57. LOG.debug("Mail from %s", envelope.mail_from)
  58. LOG.debug("Rcpt to %s", envelope.rcpt_tos)
  59. message_data = envelope.content.decode("utf8", errors="replace")
  60. # Only when debug
  61. # LOG.debug("Message data:\n")
  62. # LOG.debug(message_data)
  63. # host IP, setup via Docker network
  64. smtp = SMTP("1.1.1.1", 25)
  65. msg = Parser(policy=default).parsestr(message_data)
  66. if not envelope.rcpt_tos[0].startswith("reply+"): # Forward case
  67. LOG.debug("Forward phase, add Reply-To header")
  68. alias = envelope.rcpt_tos[0] # alias@SL
  69. app = create_app()
  70. with app.app_context():
  71. gen_email = GenEmail.get_by(email=alias)
  72. website_email = parse_srs_email(envelope.mail_from)
  73. forward_email = ForwardEmail.get_by(
  74. gen_email_id=gen_email.id, website_email=website_email
  75. )
  76. if not forward_email:
  77. LOG.debug(
  78. "create forward email for alias %s and website email %s",
  79. alias,
  80. website_email,
  81. )
  82. # todo: make sure reply_email is unique
  83. reply_email = f"reply+{random_words()}@{EMAIL_DOMAIN}"
  84. forward_email = ForwardEmail.create(
  85. gen_email_id=gen_email.id,
  86. website_email=website_email,
  87. reply_email=reply_email,
  88. )
  89. db.session.commit()
  90. # add custom header
  91. msg.add_header("X-SimpleLogin-Type", "Forward")
  92. msg.replace_header("Reply-To", forward_email.reply_email)
  93. LOG.d(
  94. "Send mail from %s to %s, mail_options %s, rcpt_options %s ",
  95. envelope.mail_from,
  96. gen_email.user.email,
  97. envelope.mail_options,
  98. envelope.rcpt_options,
  99. )
  100. smtp.send_message(
  101. msg,
  102. from_addr=envelope.mail_from,
  103. to_addrs=[gen_email.user.email], # user personal email
  104. mail_options=envelope.mail_options,
  105. rcpt_options=envelope.rcpt_options,
  106. )
  107. else:
  108. LOG.debug("Reply phase")
  109. reply_email = envelope.rcpt_tos[0]
  110. app = create_app()
  111. with app.app_context():
  112. forward_email = ForwardEmail.get_by(reply_email=reply_email)
  113. alias = forward_email.gen_email.email
  114. notify_admin(
  115. f"Reply phase used by user: {forward_email.gen_email.user.email} "
  116. )
  117. # email seems to come from alias
  118. msg.replace_header("From", alias)
  119. msg.replace_header("To", forward_email.website_email)
  120. LOG.d(
  121. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  122. alias,
  123. forward_email.website_email,
  124. envelope.mail_options,
  125. envelope.rcpt_options,
  126. )
  127. smtp.send_message(
  128. msg,
  129. from_addr=alias,
  130. to_addrs=[forward_email.website_email],
  131. mail_options=envelope.mail_options,
  132. rcpt_options=envelope.rcpt_options,
  133. )
  134. return "250 Message accepted for delivery"
  135. if __name__ == "__main__":
  136. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  137. controller.start()
  138. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  139. while True:
  140. time.sleep(10)