email_handler.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. POSTFIX_SUBMISSION_TLS,
  42. )
  43. from app.email_utils import (
  44. get_email_name,
  45. get_email_part,
  46. send_email,
  47. add_dkim_signature,
  48. get_email_domain_part,
  49. add_or_replace_header,
  50. delete_header,
  51. send_cannot_create_directory_alias,
  52. send_cannot_create_domain_alias,
  53. email_belongs_to_alias_domains,
  54. render,
  55. )
  56. from app.extensions import db
  57. from app.log import LOG
  58. from app.models import (
  59. GenEmail,
  60. ForwardEmail,
  61. ForwardEmailLog,
  62. CustomDomain,
  63. Directory,
  64. User,
  65. DeletedAlias,
  66. )
  67. from app.utils import random_string
  68. from server import create_app
  69. # fix the database connection leak issue
  70. # use this method instead of create_app
  71. def new_app():
  72. app = create_app()
  73. @app.teardown_appcontext
  74. def shutdown_session(response_or_exc):
  75. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  76. db.session.remove()
  77. # dispose the engine too
  78. db.engine.dispose()
  79. return app
  80. def try_auto_create(alias: str) -> Optional[GenEmail]:
  81. """Try to auto-create the alias using directory or catch-all domain
  82. """
  83. gen_email = try_auto_create_catch_all_domain(alias)
  84. if not gen_email:
  85. gen_email = try_auto_create_directory(alias)
  86. return gen_email
  87. def try_auto_create_directory(alias: str) -> Optional[GenEmail]:
  88. """
  89. Try to create an alias with directory
  90. """
  91. # check if alias belongs to a directory, ie having directory/anything@EMAIL_DOMAIN format
  92. if email_belongs_to_alias_domains(alias):
  93. # if there's no directory separator in the alias, no way to auto-create it
  94. if "/" not in alias and "+" not in alias and "#" not in alias:
  95. return None
  96. # alias contains one of the 3 special directory separator: "/", "+" or "#"
  97. if "/" in alias:
  98. sep = "/"
  99. elif "+" in alias:
  100. sep = "+"
  101. else:
  102. sep = "#"
  103. directory_name = alias[: alias.find(sep)]
  104. LOG.d("directory_name %s", directory_name)
  105. directory = Directory.get_by(name=directory_name)
  106. if not directory:
  107. return None
  108. dir_user: User = directory.user
  109. if not dir_user.can_create_new_alias():
  110. send_cannot_create_directory_alias(dir_user, alias, directory_name)
  111. return None
  112. # if alias has been deleted before, do not auto-create it
  113. if DeletedAlias.get_by(email=alias, user_id=directory.user_id):
  114. LOG.warning(
  115. "Alias %s was deleted before, cannot auto-create using directory %s, user %s",
  116. alias,
  117. directory_name,
  118. dir_user,
  119. )
  120. return None
  121. LOG.d("create alias %s for directory %s", alias, directory)
  122. gen_email = GenEmail.create(
  123. email=alias, user_id=directory.user_id, directory_id=directory.id,
  124. )
  125. db.session.commit()
  126. return gen_email
  127. def try_auto_create_catch_all_domain(alias: str) -> Optional[GenEmail]:
  128. """Try to create an alias with catch-all domain"""
  129. # try to create alias on-the-fly with custom-domain catch-all feature
  130. # check if alias is custom-domain alias and if the custom-domain has catch-all enabled
  131. alias_domain = get_email_domain_part(alias)
  132. custom_domain = CustomDomain.get_by(domain=alias_domain)
  133. if not custom_domain:
  134. return None
  135. # custom_domain exists
  136. if not custom_domain.catch_all:
  137. return None
  138. # custom_domain has catch-all enabled
  139. domain_user: User = custom_domain.user
  140. if not domain_user.can_create_new_alias():
  141. send_cannot_create_domain_alias(domain_user, alias, alias_domain)
  142. return None
  143. # if alias has been deleted before, do not auto-create it
  144. if DeletedAlias.get_by(email=alias, user_id=custom_domain.user_id):
  145. LOG.warning(
  146. "Alias %s was deleted before, cannot auto-create using domain catch-all %s, user %s",
  147. alias,
  148. custom_domain,
  149. domain_user,
  150. )
  151. return None
  152. LOG.d("create alias %s for domain %s", alias, custom_domain)
  153. gen_email = GenEmail.create(
  154. email=alias,
  155. user_id=custom_domain.user_id,
  156. custom_domain_id=custom_domain.id,
  157. automatic_creation=True,
  158. )
  159. db.session.commit()
  160. return gen_email
  161. def get_or_create_forward_email(
  162. website_from_header: str, gen_email: GenEmail
  163. ) -> ForwardEmail:
  164. """
  165. website_from_header can be the full-form email, i.e. "First Last <email@example.com>"
  166. """
  167. website_email = get_email_part(website_from_header)
  168. forward_email = ForwardEmail.get_by(
  169. gen_email_id=gen_email.id, website_email=website_email
  170. )
  171. if forward_email:
  172. # update the website_from if needed
  173. if forward_email.website_from != website_from_header:
  174. LOG.d("Update From header for %s", forward_email)
  175. forward_email.website_from = website_from_header
  176. db.session.commit()
  177. else:
  178. LOG.debug(
  179. "create forward email for alias %s and website email %s",
  180. gen_email,
  181. website_from_header,
  182. )
  183. # generate a reply_email, make sure it is unique
  184. # not use while loop to avoid infinite loop
  185. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  186. for _ in range(1000):
  187. if not ForwardEmail.get_by(reply_email=reply_email):
  188. # found!
  189. break
  190. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  191. forward_email = ForwardEmail.create(
  192. gen_email_id=gen_email.id,
  193. website_email=website_email,
  194. website_from=website_from_header,
  195. reply_email=reply_email,
  196. )
  197. db.session.commit()
  198. return forward_email
  199. def handle_forward(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> str:
  200. """return *status_code message*"""
  201. alias = rcpt_to.lower() # alias@SL
  202. gen_email = GenEmail.get_by(email=alias)
  203. if not gen_email:
  204. LOG.d("alias %s not exist. Try to see if it can be created on the fly", alias)
  205. gen_email = try_auto_create(alias)
  206. if not gen_email:
  207. LOG.d("alias %s cannot be created on-the-fly, return 510", alias)
  208. return "510 Email not exist"
  209. mailbox_email = gen_email.mailbox_email()
  210. forward_email = get_or_create_forward_email(msg["From"], gen_email)
  211. forward_log = ForwardEmailLog.create(forward_id=forward_email.id)
  212. if gen_email.enabled:
  213. # add custom header
  214. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  215. # remove reply-to header if present
  216. delete_header(msg, "Reply-To")
  217. # change the from header so the sender comes from @SL
  218. # so it can pass DMARC check
  219. # replace the email part in from: header
  220. website_from_header = msg["From"]
  221. website_email = get_email_part(website_from_header)
  222. from_header = (
  223. get_email_name(website_from_header)
  224. + ("" if get_email_name(website_from_header) == "" else " - ")
  225. + website_email.replace("@", " at ")
  226. + f" <{forward_email.reply_email}>"
  227. )
  228. msg.replace_header("From", from_header)
  229. LOG.d("new from header:%s", from_header)
  230. # add List-Unsubscribe header
  231. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{gen_email.id}"
  232. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  233. add_or_replace_header(
  234. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  235. )
  236. add_dkim_signature(msg, EMAIL_DOMAIN)
  237. LOG.d(
  238. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  239. website_email,
  240. mailbox_email,
  241. envelope.mail_options,
  242. envelope.rcpt_options,
  243. )
  244. # smtp.send_message has UnicodeEncodeErroremail issue
  245. # encode message raw directly instead
  246. msg_raw = msg.as_string().encode()
  247. smtp.sendmail(
  248. forward_email.reply_email,
  249. mailbox_email,
  250. msg_raw,
  251. envelope.mail_options,
  252. envelope.rcpt_options,
  253. )
  254. else:
  255. LOG.d("%s is disabled, do not forward", gen_email)
  256. forward_log.blocked = True
  257. db.session.commit()
  258. return "250 Message accepted for delivery"
  259. def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> str:
  260. reply_email = rcpt_to.lower()
  261. # reply_email must end with EMAIL_DOMAIN
  262. if not reply_email.endswith(EMAIL_DOMAIN):
  263. LOG.warning(f"Reply email {reply_email} has wrong domain")
  264. return "550 wrong reply email"
  265. forward_email = ForwardEmail.get_by(reply_email=reply_email)
  266. if not forward_email:
  267. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  268. return "550 wrong reply email"
  269. alias: str = forward_email.gen_email.email
  270. alias_domain = alias[alias.find("@") + 1 :]
  271. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  272. if not email_belongs_to_alias_domains(alias):
  273. if not CustomDomain.get_by(domain=alias_domain):
  274. return "550 alias unknown by SimpleLogin"
  275. gen_email = forward_email.gen_email
  276. user = gen_email.user
  277. mailbox_email = gen_email.mailbox_email()
  278. # bounce email initiated by Postfix
  279. # can happen in case emails cannot be delivered to user-email
  280. # in this case Postfix will try to send a bounce report to original sender, which is
  281. # the "reply email"
  282. if envelope.mail_from == "<>":
  283. LOG.error(
  284. "Bounce when sending to alias %s, user %s, from header: %s",
  285. alias,
  286. gen_email.user,
  287. msg["From"],
  288. )
  289. handle_bounce(
  290. alias, envelope, forward_email, gen_email, msg, smtp, user, mailbox_email
  291. )
  292. return "550 ignored"
  293. # only mailbox can send email to the reply-email
  294. if envelope.mail_from.lower() != mailbox_email.lower():
  295. LOG.warning(
  296. f"Reply email can only be used by user email. Actual mail_from: %s. msg from header: %s, User email %s. reply_email %s",
  297. envelope.mail_from,
  298. msg["From"],
  299. mailbox_email,
  300. reply_email,
  301. )
  302. user = gen_email.user
  303. send_email(
  304. mailbox_email,
  305. f"Reply from your alias {alias} only works from your mailbox",
  306. render(
  307. "transactional/reply-must-use-personal-email.txt",
  308. name=user.name,
  309. alias=alias,
  310. sender=envelope.mail_from,
  311. mailbox_email=mailbox_email,
  312. ),
  313. render(
  314. "transactional/reply-must-use-personal-email.html",
  315. name=user.name,
  316. alias=alias,
  317. sender=envelope.mail_from,
  318. mailbox_email=mailbox_email,
  319. ),
  320. )
  321. # Notify sender that they cannot send emails to this address
  322. send_email(
  323. envelope.mail_from,
  324. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  325. render(
  326. "transactional/send-from-alias-from-unknown-sender.txt",
  327. sender=envelope.mail_from,
  328. reply_email=reply_email,
  329. ),
  330. "",
  331. )
  332. return "550 ignored"
  333. delete_header(msg, "DKIM-Signature")
  334. # the email comes from alias
  335. msg.replace_header("From", alias)
  336. # some email providers like ProtonMail adds automatically the Reply-To field
  337. # make sure to delete it
  338. delete_header(msg, "Reply-To")
  339. msg.replace_header("To", forward_email.website_email)
  340. # add List-Unsubscribe header
  341. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{forward_email.gen_email_id}"
  342. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  343. add_or_replace_header(msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click")
  344. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  345. delete_header(msg, "Received-SPF")
  346. LOG.d(
  347. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  348. alias,
  349. forward_email.website_email,
  350. envelope.mail_options,
  351. envelope.rcpt_options,
  352. )
  353. if alias_domain in ALIAS_DOMAINS:
  354. add_dkim_signature(msg, alias_domain)
  355. # add DKIM-Signature for custom-domain alias
  356. else:
  357. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  358. if custom_domain.dkim_verified:
  359. add_dkim_signature(msg, alias_domain)
  360. msg_raw = msg.as_string().encode()
  361. smtp.sendmail(
  362. alias,
  363. forward_email.website_email,
  364. msg_raw,
  365. envelope.mail_options,
  366. envelope.rcpt_options,
  367. )
  368. ForwardEmailLog.create(forward_id=forward_email.id, is_reply=True)
  369. db.session.commit()
  370. return "250 Message accepted for delivery"
  371. def handle_bounce(
  372. alias, envelope, forward_email, gen_email, msg, smtp, user, mailbox_email
  373. ):
  374. ForwardEmailLog.create(forward_id=forward_email.id, bounced=True)
  375. db.session.commit()
  376. nb_bounced = ForwardEmailLog.filter_by(
  377. forward_id=forward_email.id, bounced=True
  378. ).count()
  379. disable_alias_link = f"{URL}/dashboard/unsubscribe/{gen_email.id}"
  380. # inform user if this is the first bounced email
  381. if nb_bounced == 1:
  382. LOG.d(
  383. "Inform user %s about bounced email sent by %s to alias %s",
  384. user,
  385. forward_email.website_from,
  386. alias,
  387. )
  388. send_email(
  389. mailbox_email,
  390. f"Email from {forward_email.website_from} to {alias} cannot be delivered to your inbox",
  391. render(
  392. "transactional/bounced-email.txt",
  393. name=user.name,
  394. alias=alias,
  395. website_from=forward_email.website_from,
  396. website_email=forward_email.website_email,
  397. disable_alias_link=disable_alias_link,
  398. ),
  399. render(
  400. "transactional/bounced-email.html",
  401. name=user.name,
  402. alias=alias,
  403. website_from=forward_email.website_from,
  404. website_email=forward_email.website_email,
  405. disable_alias_link=disable_alias_link,
  406. ),
  407. bounced_email=msg,
  408. )
  409. # disable the alias the second time email is bounced
  410. elif nb_bounced >= 2:
  411. LOG.d(
  412. "Bounce happens again with alias %s from %s. Disable alias now ",
  413. alias,
  414. forward_email.website_from,
  415. )
  416. gen_email.enabled = False
  417. db.session.commit()
  418. send_email(
  419. mailbox_email,
  420. f"Alias {alias} has been disabled due to second undelivered email from {forward_email.website_from}",
  421. render(
  422. "transactional/automatic-disable-alias.txt",
  423. name=user.name,
  424. alias=alias,
  425. website_from=forward_email.website_from,
  426. website_email=forward_email.website_email,
  427. ),
  428. render(
  429. "transactional/automatic-disable-alias.html",
  430. name=user.name,
  431. alias=alias,
  432. website_from=forward_email.website_from,
  433. website_email=forward_email.website_email,
  434. ),
  435. bounced_email=msg,
  436. )
  437. class MailHandler:
  438. async def handle_DATA(self, server, session, envelope):
  439. LOG.debug(">>> New message <<<")
  440. LOG.debug("Mail from %s", envelope.mail_from)
  441. LOG.debug("Rcpt to %s", envelope.rcpt_tos)
  442. message_data = envelope.content.decode("utf8", errors="replace")
  443. if POSTFIX_SUBMISSION_TLS:
  444. smtp = SMTP(POSTFIX_SERVER, 587)
  445. smtp.starttls()
  446. else:
  447. smtp = SMTP(POSTFIX_SERVER, 25)
  448. msg = Parser(policy=SMTPUTF8).parsestr(message_data)
  449. for rcpt_to in envelope.rcpt_tos:
  450. # Reply case
  451. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  452. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  453. LOG.debug("Reply phase")
  454. app = new_app()
  455. with app.app_context():
  456. return handle_reply(envelope, smtp, msg, rcpt_to)
  457. else: # Forward case
  458. LOG.debug("Forward phase")
  459. app = new_app()
  460. with app.app_context():
  461. return handle_forward(envelope, smtp, msg, rcpt_to)
  462. if __name__ == "__main__":
  463. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  464. controller.start()
  465. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  466. while True:
  467. time.sleep(2)