email_handler.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. """
  2. Handle the email *forward* and *reply*. phase. There are 3 actors:
  3. - contact: 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 contact.
  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: @contact
  10. rcpt to: @personal_email
  11. Header:
  12. From: @contact
  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: @contact
  18. rcpt to: @contact
  19. Header:
  20. From: alias@sl.co # so for contact the email comes from alias. magic HERE
  21. To: @contact
  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. - @contact
  26. """
  27. import email
  28. import time
  29. import uuid
  30. from email import encoders
  31. from email.message import Message
  32. from email.mime.application import MIMEApplication
  33. from email.mime.multipart import MIMEMultipart
  34. from email.utils import parseaddr
  35. from io import BytesIO
  36. from smtplib import SMTP
  37. from typing import Optional
  38. from aiosmtpd.controller import Controller
  39. from aiosmtpd.smtp import Envelope
  40. from app import pgp_utils, s3
  41. from app.config import (
  42. EMAIL_DOMAIN,
  43. POSTFIX_SERVER,
  44. URL,
  45. ALIAS_DOMAINS,
  46. POSTFIX_SUBMISSION_TLS,
  47. UNSUBSCRIBER,
  48. )
  49. from app.email_utils import (
  50. send_email,
  51. add_dkim_signature,
  52. get_email_domain_part,
  53. add_or_replace_header,
  54. delete_header,
  55. send_cannot_create_directory_alias,
  56. send_cannot_create_domain_alias,
  57. email_belongs_to_alias_domains,
  58. render,
  59. get_orig_message_from_bounce,
  60. delete_all_headers_except,
  61. new_addr,
  62. get_addrs_from_header,
  63. get_spam_info,
  64. get_orig_message_from_spamassassin_report,
  65. )
  66. from app.extensions import db
  67. from app.log import LOG
  68. from app.models import (
  69. Alias,
  70. Contact,
  71. EmailLog,
  72. CustomDomain,
  73. Directory,
  74. User,
  75. DeletedAlias,
  76. RefusedEmail,
  77. )
  78. from app.utils import random_string
  79. from server import create_app
  80. # used when an alias receives email from its own mailbox
  81. # can happen when user "Reply All" on some email clients
  82. _SELF_FORWARDING_STATUS = "550 SL self-forward"
  83. # fix the database connection leak issue
  84. # use this method instead of create_app
  85. def new_app():
  86. app = create_app()
  87. @app.teardown_appcontext
  88. def shutdown_session(response_or_exc):
  89. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  90. db.session.remove()
  91. # dispose the engine too
  92. db.engine.dispose()
  93. return app
  94. def try_auto_create(address: str) -> Optional[Alias]:
  95. """Try to auto-create the alias using directory or catch-all domain
  96. """
  97. alias = try_auto_create_catch_all_domain(address)
  98. if not alias:
  99. alias = try_auto_create_directory(address)
  100. return alias
  101. def try_auto_create_directory(address: str) -> Optional[Alias]:
  102. """
  103. Try to create an alias with directory
  104. """
  105. # check if alias belongs to a directory, ie having directory/anything@EMAIL_DOMAIN format
  106. if email_belongs_to_alias_domains(address):
  107. # if there's no directory separator in the alias, no way to auto-create it
  108. if "/" not in address and "+" not in address and "#" not in address:
  109. return None
  110. # alias contains one of the 3 special directory separator: "/", "+" or "#"
  111. if "/" in address:
  112. sep = "/"
  113. elif "+" in address:
  114. sep = "+"
  115. else:
  116. sep = "#"
  117. directory_name = address[: address.find(sep)]
  118. LOG.d("directory_name %s", directory_name)
  119. directory = Directory.get_by(name=directory_name)
  120. if not directory:
  121. return None
  122. dir_user: User = directory.user
  123. if not dir_user.can_create_new_alias():
  124. send_cannot_create_directory_alias(dir_user, address, directory_name)
  125. return None
  126. # if alias has been deleted before, do not auto-create it
  127. if DeletedAlias.get_by(email=address, user_id=directory.user_id):
  128. LOG.warning(
  129. "Alias %s was deleted before, cannot auto-create using directory %s, user %s",
  130. address,
  131. directory_name,
  132. dir_user,
  133. )
  134. return None
  135. LOG.d("create alias %s for directory %s", address, directory)
  136. alias = Alias.create(
  137. email=address,
  138. user_id=directory.user_id,
  139. directory_id=directory.id,
  140. mailbox_id=dir_user.default_mailbox_id,
  141. )
  142. db.session.commit()
  143. return alias
  144. def try_auto_create_catch_all_domain(address: str) -> Optional[Alias]:
  145. """Try to create an alias with catch-all domain"""
  146. # try to create alias on-the-fly with custom-domain catch-all feature
  147. # check if alias is custom-domain alias and if the custom-domain has catch-all enabled
  148. alias_domain = get_email_domain_part(address)
  149. custom_domain = CustomDomain.get_by(domain=alias_domain)
  150. if not custom_domain:
  151. return None
  152. # custom_domain exists
  153. if not custom_domain.catch_all:
  154. return None
  155. # custom_domain has catch-all enabled
  156. domain_user: User = custom_domain.user
  157. if not domain_user.can_create_new_alias():
  158. send_cannot_create_domain_alias(domain_user, address, alias_domain)
  159. return None
  160. # if alias has been deleted before, do not auto-create it
  161. if DeletedAlias.get_by(email=address, user_id=custom_domain.user_id):
  162. LOG.warning(
  163. "Alias %s was deleted before, cannot auto-create using domain catch-all %s, user %s",
  164. address,
  165. custom_domain,
  166. domain_user,
  167. )
  168. return None
  169. LOG.d("create alias %s for domain %s", address, custom_domain)
  170. alias = Alias.create(
  171. email=address,
  172. user_id=custom_domain.user_id,
  173. custom_domain_id=custom_domain.id,
  174. automatic_creation=True,
  175. mailbox_id=domain_user.default_mailbox_id,
  176. )
  177. db.session.commit()
  178. return alias
  179. def get_or_create_contact(website_from_header: str, alias: Alias) -> Contact:
  180. """
  181. website_from_header can be the full-form email, i.e. "First Last <email@example.com>"
  182. """
  183. _, website_email = parseaddr(website_from_header)
  184. contact = Contact.get_by(alias_id=alias.id, website_email=website_email)
  185. if contact:
  186. # update the website_from if needed
  187. if contact.website_from != website_from_header:
  188. LOG.d("Update From header for %s", contact)
  189. contact.website_from = website_from_header
  190. db.session.commit()
  191. else:
  192. LOG.debug(
  193. "create forward email for alias %s and website email %s",
  194. alias,
  195. website_from_header,
  196. )
  197. reply_email = generate_reply_email()
  198. contact = Contact.create(
  199. user_id=alias.user_id,
  200. alias_id=alias.id,
  201. website_email=website_email,
  202. website_from=website_from_header,
  203. reply_email=reply_email,
  204. )
  205. db.session.commit()
  206. return contact
  207. def replace_header_when_forward(msg: Message, alias: Alias, header: str):
  208. """
  209. Replace CC or To header by Reply emails in forward phase
  210. """
  211. addrs = get_addrs_from_header(msg, header)
  212. # Nothing to do
  213. if not addrs:
  214. return
  215. new_addrs: [str] = []
  216. need_replace = False
  217. for addr in addrs:
  218. name, email = parseaddr(addr)
  219. # no transformation when alias is already in the header
  220. if email == alias.email:
  221. new_addrs.append(addr)
  222. continue
  223. contact = Contact.get_by(alias_id=alias.id, website_email=email)
  224. if contact:
  225. # update the website_from if needed
  226. if contact.website_from != addr:
  227. LOG.d("Update website_from for %s to %s", contact, addr)
  228. contact.website_from = addr
  229. db.session.commit()
  230. else:
  231. LOG.debug(
  232. "create contact for alias %s and email %s, header %s",
  233. alias,
  234. email,
  235. header,
  236. )
  237. reply_email = generate_reply_email()
  238. contact = Contact.create(
  239. user_id=alias.user_id,
  240. alias_id=alias.id,
  241. website_email=email,
  242. website_from=addr,
  243. reply_email=reply_email,
  244. is_cc=header.lower() == "cc",
  245. )
  246. db.session.commit()
  247. new_addrs.append(
  248. new_addr(contact.website_from, contact.reply_email, alias.user)
  249. )
  250. need_replace = True
  251. if need_replace:
  252. new_header = ",".join(new_addrs)
  253. LOG.d("Replace %s header, old: %s, new: %s", header, msg[header], new_header)
  254. add_or_replace_header(msg, header, new_header)
  255. else:
  256. LOG.d("No need to replace %s header", header)
  257. def replace_header_when_reply(msg: Message, alias: Alias, header: str):
  258. """
  259. Replace CC or To Reply emails by original emails
  260. """
  261. addrs = get_addrs_from_header(msg, header)
  262. # Nothing to do
  263. if not addrs:
  264. return
  265. new_addrs: [str] = []
  266. for addr in addrs:
  267. name, email = parseaddr(addr)
  268. # no transformation when alias is already in the header
  269. if email == alias.email:
  270. continue
  271. contact = Contact.get_by(reply_email=email)
  272. if not contact:
  273. LOG.warning(
  274. "%s email in reply phase %s must be reply emails", header, email
  275. )
  276. # still keep this email in header
  277. new_addrs.append(addr)
  278. continue
  279. new_addrs.append(contact.website_from or contact.website_email)
  280. new_header = ",".join(new_addrs)
  281. LOG.d("Replace %s header, old: %s, new: %s", header, msg[header], new_header)
  282. add_or_replace_header(msg, header, new_header)
  283. def generate_reply_email():
  284. # generate a reply_email, make sure it is unique
  285. # not use while loop to avoid infinite loop
  286. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  287. for _ in range(1000):
  288. if not Contact.get_by(reply_email=reply_email):
  289. # found!
  290. break
  291. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  292. return reply_email
  293. def should_append_alias(msg: Message, address: str):
  294. """whether an alias should be appended to TO header in message"""
  295. if msg["To"] and address in msg["To"]:
  296. return False
  297. if msg["Cc"] and address in msg["Cc"]:
  298. return False
  299. return True
  300. def prepare_pgp_message(orig_msg: Message, pgp_fingerprint: str):
  301. msg = MIMEMultipart("encrypted", protocol="application/pgp-encrypted")
  302. # copy all headers from original message except the "Content-Type"
  303. for i in reversed(range(len(orig_msg._headers))):
  304. header_name = orig_msg._headers[i][0].lower()
  305. if header_name != "Content-Type".lower():
  306. msg[header_name] = orig_msg._headers[i][1]
  307. # Delete unnecessary headers in orig_msg except to save space
  308. delete_all_headers_except(
  309. orig_msg,
  310. [
  311. "MIME-Version",
  312. "Content-Type",
  313. "Content-Disposition",
  314. "Content-Transfer-Encoding",
  315. ],
  316. )
  317. first = MIMEApplication(
  318. _subtype="pgp-encrypted", _encoder=encoders.encode_7or8bit, _data=""
  319. )
  320. first.set_payload("Version: 1")
  321. msg.attach(first)
  322. second = MIMEApplication("octet-stream", _encoder=encoders.encode_7or8bit)
  323. second.add_header("Content-Disposition", "inline")
  324. # encrypt original message
  325. encrypted_data = pgp_utils.encrypt(orig_msg.as_string(), pgp_fingerprint)
  326. second.set_payload(encrypted_data)
  327. msg.attach(second)
  328. return msg
  329. def handle_forward(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> (bool, str):
  330. """return whether an email has been delivered and
  331. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  332. """
  333. address = rcpt_to.lower() # alias@SL
  334. alias = Alias.get_by(email=address)
  335. if not alias:
  336. LOG.d("alias %s not exist. Try to see if it can be created on the fly", address)
  337. alias = try_auto_create(address)
  338. if not alias:
  339. LOG.d("alias %s cannot be created on-the-fly, return 550", address)
  340. return False, "550 SL Email not exist"
  341. mailbox = alias.mailbox
  342. mailbox_email = mailbox.email
  343. user = alias.user
  344. # Sometimes when user clicks on "reply all"
  345. # an email is sent to the same alias that the previous message is destined to
  346. if envelope.mail_from == mailbox_email:
  347. # nothing to do
  348. LOG.d("Forward from %s to %s, nothing to do", envelope.mail_from, mailbox_email)
  349. return False, _SELF_FORWARDING_STATUS
  350. contact = get_or_create_contact(msg["From"], alias)
  351. spam_check = True
  352. # create PGP email if needed
  353. if mailbox.pgp_finger_print and user.is_premium():
  354. LOG.d("Encrypt message using mailbox %s", mailbox)
  355. msg = prepare_pgp_message(msg, mailbox.pgp_finger_print)
  356. # no need to spam check for encrypted message
  357. spam_check = False
  358. if spam_check:
  359. is_spam, spam_status = get_spam_info(msg)
  360. if is_spam:
  361. LOG.warning("Email detected as spam. Alias: %s, from: %s", alias, contact)
  362. handle_spam(contact, alias, msg, user, mailbox_email, spam_status)
  363. return False, "550 SL ignored"
  364. forward_log = EmailLog.create(contact_id=contact.id, user_id=contact.user_id)
  365. if alias.enabled:
  366. # add custom header
  367. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  368. # remove reply-to & sender header if present
  369. delete_header(msg, "Reply-To")
  370. delete_header(msg, "Sender")
  371. # change the from header so the sender comes from @SL
  372. # so it can pass DMARC check
  373. # replace the email part in from: header
  374. contact_from_header = msg["From"]
  375. contact_name, contact_email = parseaddr(contact_from_header)
  376. new_from_header = new_addr(contact_from_header, contact.reply_email, user)
  377. add_or_replace_header(msg, "From", new_from_header)
  378. LOG.d("new_from_header:%s, old header %s", new_from_header, contact_from_header)
  379. # replace CC & To emails by reply-email for all emails that are not alias
  380. replace_header_when_forward(msg, alias, "Cc")
  381. replace_header_when_forward(msg, alias, "To")
  382. # append alias into the TO header if it's not present in To or CC
  383. if should_append_alias(msg, alias.email):
  384. LOG.d("append alias %s to TO header %s", alias, msg["To"])
  385. if msg["To"]:
  386. to_header = msg["To"] + "," + alias.email
  387. else:
  388. to_header = alias.email
  389. add_or_replace_header(msg, "To", to_header.strip())
  390. # add List-Unsubscribe header
  391. if UNSUBSCRIBER:
  392. unsubscribe_link = f"mailto:{UNSUBSCRIBER}?subject={alias.id}="
  393. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  394. else:
  395. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  396. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  397. add_or_replace_header(
  398. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  399. )
  400. add_dkim_signature(msg, EMAIL_DOMAIN)
  401. LOG.d(
  402. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  403. contact_email,
  404. mailbox_email,
  405. envelope.mail_options,
  406. envelope.rcpt_options,
  407. )
  408. # smtp.send_message has UnicodeEncodeErroremail issue
  409. # encode message raw directly instead
  410. smtp.sendmail(
  411. contact.reply_email,
  412. mailbox_email,
  413. msg.as_bytes(),
  414. envelope.mail_options,
  415. envelope.rcpt_options,
  416. )
  417. else:
  418. LOG.d("%s is disabled, do not forward", alias)
  419. forward_log.blocked = True
  420. db.session.commit()
  421. return True, "250 Message accepted for delivery"
  422. def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> (bool, str):
  423. """
  424. return whether an email has been delivered and
  425. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  426. """
  427. reply_email = rcpt_to.lower()
  428. # reply_email must end with EMAIL_DOMAIN
  429. if not reply_email.endswith(EMAIL_DOMAIN):
  430. LOG.warning(f"Reply email {reply_email} has wrong domain")
  431. return False, "550 SL wrong reply email"
  432. contact = Contact.get_by(reply_email=reply_email)
  433. if not contact:
  434. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  435. return False, "550 SL wrong reply email"
  436. alias = contact.alias
  437. address: str = contact.alias.email
  438. alias_domain = address[address.find("@") + 1 :]
  439. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  440. if not email_belongs_to_alias_domains(alias.email):
  441. if not CustomDomain.get_by(domain=alias_domain):
  442. return False, "550 SL alias unknown by SimpleLogin"
  443. user = alias.user
  444. mailbox_email = alias.mailbox_email()
  445. # bounce email initiated by Postfix
  446. # can happen in case emails cannot be delivered to user-email
  447. # in this case Postfix will try to send a bounce report to original sender, which is
  448. # the "reply email"
  449. if envelope.mail_from == "<>":
  450. LOG.warning(
  451. "Bounce when sending to alias %s from %s, user %s",
  452. alias,
  453. contact.website_from,
  454. alias.user,
  455. )
  456. handle_bounce(contact, alias, msg, user, mailbox_email)
  457. return False, "550 SL ignored"
  458. # only mailbox can send email to the reply-email
  459. if envelope.mail_from.lower() != mailbox_email.lower():
  460. LOG.warning(
  461. f"Reply email can only be used by mailbox. "
  462. f"Actual mail_from: %s. msg from header: %s, Mailbox %s. reply_email %s",
  463. envelope.mail_from,
  464. msg["From"],
  465. mailbox_email,
  466. reply_email,
  467. )
  468. send_email(
  469. mailbox_email,
  470. f"Reply from your alias {alias.email} only works from your mailbox",
  471. render(
  472. "transactional/reply-must-use-personal-email.txt",
  473. name=user.name,
  474. alias=alias.email,
  475. sender=envelope.mail_from,
  476. mailbox_email=mailbox_email,
  477. ),
  478. render(
  479. "transactional/reply-must-use-personal-email.html",
  480. name=user.name,
  481. alias=alias.email,
  482. sender=envelope.mail_from,
  483. mailbox_email=mailbox_email,
  484. ),
  485. )
  486. # Notify sender that they cannot send emails to this address
  487. send_email(
  488. envelope.mail_from,
  489. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  490. render(
  491. "transactional/send-from-alias-from-unknown-sender.txt",
  492. sender=envelope.mail_from,
  493. reply_email=reply_email,
  494. ),
  495. "",
  496. )
  497. return False, "550 SL ignored"
  498. delete_header(msg, "DKIM-Signature")
  499. delete_header(msg, "Received")
  500. # make the email comes from alias
  501. add_or_replace_header(msg, "From", alias.email)
  502. # some email providers like ProtonMail adds automatically the Reply-To field
  503. # make sure to delete it
  504. delete_header(msg, "Reply-To")
  505. # remove sender header if present as this could reveal user real email
  506. delete_header(msg, "Sender")
  507. delete_header(msg, "X-Sender")
  508. replace_header_when_reply(msg, alias, "To")
  509. replace_header_when_reply(msg, alias, "Cc")
  510. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  511. delete_header(msg, "Received-SPF")
  512. LOG.d(
  513. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  514. alias.email,
  515. contact.website_email,
  516. envelope.mail_options,
  517. envelope.rcpt_options,
  518. )
  519. if alias_domain in ALIAS_DOMAINS:
  520. add_dkim_signature(msg, alias_domain)
  521. # add DKIM-Signature for custom-domain alias
  522. else:
  523. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  524. if custom_domain.dkim_verified:
  525. add_dkim_signature(msg, alias_domain)
  526. smtp.sendmail(
  527. alias.email,
  528. contact.website_email,
  529. msg.as_bytes(),
  530. envelope.mail_options,
  531. envelope.rcpt_options,
  532. )
  533. EmailLog.create(contact_id=contact.id, is_reply=True, user_id=contact.user_id)
  534. db.session.commit()
  535. return True, "250 Message accepted for delivery"
  536. def handle_bounce(
  537. contact: Contact, alias: Alias, msg: Message, user: User, mailbox_email: str
  538. ):
  539. address = alias.email
  540. fel: EmailLog = EmailLog.create(
  541. contact_id=contact.id, bounced=True, user_id=contact.user_id
  542. )
  543. db.session.commit()
  544. nb_bounced = EmailLog.filter_by(contact_id=contact.id, bounced=True).count()
  545. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  546. # Store the bounced email
  547. orig_msg = get_orig_message_from_bounce(msg)
  548. # generate a name for the email
  549. random_name = str(uuid.uuid4())
  550. full_report_path = f"refused-emails/full-{random_name}.eml"
  551. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  552. file_path = None
  553. if orig_msg:
  554. file_path = f"refused-emails/{random_name}.eml"
  555. s3.upload_email_from_bytesio(
  556. file_path, BytesIO(orig_msg.as_bytes()), random_name
  557. )
  558. refused_email = RefusedEmail.create(
  559. path=file_path, full_report_path=full_report_path, user_id=user.id
  560. )
  561. db.session.flush()
  562. fel.refused_email_id = refused_email.id
  563. db.session.commit()
  564. LOG.d("Create refused email %s", refused_email)
  565. refused_email_url = URL + f"/dashboard/refused_email?highlight_id=" + str(fel.id)
  566. # inform user if this is the first bounced email
  567. if nb_bounced == 1:
  568. LOG.d(
  569. "Inform user %s about bounced email sent by %s to alias %s",
  570. user,
  571. contact.website_from,
  572. address,
  573. )
  574. send_email(
  575. # use user mail here as only user is authenticated to see the refused email
  576. user.email,
  577. f"Email from {contact.website_from} to {address} cannot be delivered to your inbox",
  578. render(
  579. "transactional/bounced-email.txt",
  580. name=user.name,
  581. alias=alias,
  582. website_from=contact.website_from,
  583. website_email=contact.website_email,
  584. disable_alias_link=disable_alias_link,
  585. refused_email_url=refused_email_url,
  586. mailbox_email=mailbox_email,
  587. ),
  588. render(
  589. "transactional/bounced-email.html",
  590. name=user.name,
  591. alias=alias,
  592. website_from=contact.website_from,
  593. website_email=contact.website_email,
  594. disable_alias_link=disable_alias_link,
  595. refused_email_url=refused_email_url,
  596. mailbox_email=mailbox_email,
  597. ),
  598. # cannot include bounce email as it can contain spammy text
  599. # bounced_email=msg,
  600. )
  601. # disable the alias the second time email is bounced
  602. elif nb_bounced >= 2:
  603. LOG.d(
  604. "Bounce happens again with alias %s from %s. Disable alias now ",
  605. address,
  606. contact.website_from,
  607. )
  608. alias.enabled = False
  609. db.session.commit()
  610. send_email(
  611. # use user mail here as only user is authenticated to see the refused email
  612. user.email,
  613. f"Alias {address} has been disabled due to second undelivered email from {contact.website_from}",
  614. render(
  615. "transactional/automatic-disable-alias.txt",
  616. name=user.name,
  617. alias=alias,
  618. website_from=contact.website_from,
  619. website_email=contact.website_email,
  620. refused_email_url=refused_email_url,
  621. mailbox_email=mailbox_email,
  622. ),
  623. render(
  624. "transactional/automatic-disable-alias.html",
  625. name=user.name,
  626. alias=alias,
  627. website_from=contact.website_from,
  628. website_email=contact.website_email,
  629. refused_email_url=refused_email_url,
  630. mailbox_email=mailbox_email,
  631. ),
  632. # cannot include bounce email as it can contain spammy text
  633. # bounced_email=msg,
  634. )
  635. def handle_spam(
  636. contact: Contact,
  637. alias: Alias,
  638. msg: Message,
  639. user: User,
  640. mailbox_email: str,
  641. spam_status: str,
  642. ):
  643. email_log: EmailLog = EmailLog.create(
  644. contact_id=contact.id,
  645. user_id=contact.user_id,
  646. is_spam=True,
  647. spam_status=spam_status,
  648. )
  649. db.session.commit()
  650. # Store the report & original email
  651. orig_msg = get_orig_message_from_spamassassin_report(msg)
  652. # generate a name for the email
  653. random_name = str(uuid.uuid4())
  654. full_report_path = f"spams/full-{random_name}.eml"
  655. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  656. file_path = None
  657. if orig_msg:
  658. file_path = f"spams/{random_name}.eml"
  659. s3.upload_email_from_bytesio(
  660. file_path, BytesIO(orig_msg.as_bytes()), random_name
  661. )
  662. refused_email = RefusedEmail.create(
  663. path=file_path, full_report_path=full_report_path, user_id=user.id
  664. )
  665. db.session.flush()
  666. email_log.refused_email_id = refused_email.id
  667. db.session.commit()
  668. LOG.d("Create spam email %s", refused_email)
  669. refused_email_url = (
  670. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  671. )
  672. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  673. # inform user
  674. LOG.d(
  675. "Inform user %s about spam email sent by %s to alias %s",
  676. user,
  677. contact.website_from,
  678. alias.email,
  679. )
  680. send_email(
  681. mailbox_email,
  682. f"Email from {contact.website_from} to {alias.email} is detected as spam",
  683. render(
  684. "transactional/spam-email.txt",
  685. name=user.name,
  686. alias=alias,
  687. website_from=contact.website_from,
  688. website_email=contact.website_email,
  689. disable_alias_link=disable_alias_link,
  690. refused_email_url=refused_email_url,
  691. ),
  692. render(
  693. "transactional/spam-email.html",
  694. name=user.name,
  695. alias=alias,
  696. website_from=contact.website_from,
  697. website_email=contact.website_email,
  698. disable_alias_link=disable_alias_link,
  699. refused_email_url=refused_email_url,
  700. ),
  701. )
  702. def handle_unsubscribe(envelope: Envelope):
  703. msg = email.message_from_bytes(envelope.original_content)
  704. # format: alias_id:
  705. subject = msg["Subject"]
  706. try:
  707. alias_id = int(subject[:-1])
  708. alias = Alias.get(alias_id)
  709. except Exception:
  710. LOG.warning("Cannot parse alias from subject %s", msg["Subject"])
  711. return "550 SL ignored"
  712. if not alias:
  713. LOG.warning("No such alias %s", alias_id)
  714. return "550 SL ignored"
  715. # This sender cannot unsubscribe
  716. if alias.mailbox_email() != envelope.mail_from:
  717. LOG.d("%s cannot disable alias %s", envelope.mail_from, alias)
  718. return "550 SL ignored"
  719. # Sender is owner of this alias
  720. alias.enabled = False
  721. db.session.commit()
  722. user = alias.user
  723. enable_alias_url = URL + f"/dashboard/?highlight_alias_id={alias.id}"
  724. send_email(
  725. envelope.mail_from,
  726. f"Alias {alias.email} has been disabled successfully",
  727. render(
  728. "transactional/unsubscribe-disable-alias.txt",
  729. user=user,
  730. alias=alias.email,
  731. enable_alias_url=enable_alias_url,
  732. ),
  733. render(
  734. "transactional/unsubscribe-disable-alias.html",
  735. user=user,
  736. alias=alias.email,
  737. enable_alias_url=enable_alias_url,
  738. ),
  739. )
  740. return "250 Unsubscribe request accepted"
  741. class MailHandler:
  742. async def handle_DATA(self, server, session, envelope: Envelope):
  743. LOG.debug(
  744. "===>> New message, mail from %s, rctp tos %s ",
  745. envelope.mail_from,
  746. envelope.rcpt_tos,
  747. )
  748. if POSTFIX_SUBMISSION_TLS:
  749. smtp = SMTP(POSTFIX_SERVER, 587)
  750. smtp.starttls()
  751. else:
  752. smtp = SMTP(POSTFIX_SERVER, 25)
  753. # unsubscribe request
  754. if UNSUBSCRIBER and envelope.rcpt_tos == [UNSUBSCRIBER]:
  755. LOG.d("Handle unsubscribe request from %s", envelope.mail_from)
  756. app = new_app()
  757. with app.app_context():
  758. return handle_unsubscribe(envelope)
  759. # result of all deliveries
  760. # each element is a couple of whether the delivery is successful and the smtp status
  761. res: [(bool, str)] = []
  762. for rcpt_to in envelope.rcpt_tos:
  763. msg = email.message_from_bytes(envelope.original_content)
  764. # Reply case
  765. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  766. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  767. LOG.debug(">>> Reply phase %s -> %s", envelope.mail_from, rcpt_to)
  768. app = new_app()
  769. with app.app_context():
  770. is_delivered, smtp_status = handle_reply(
  771. envelope, smtp, msg, rcpt_to
  772. )
  773. res.append((is_delivered, smtp_status))
  774. else: # Forward case
  775. LOG.debug(">>> Forward phase %s -> %s", envelope.mail_from, rcpt_to)
  776. app = new_app()
  777. with app.app_context():
  778. is_delivered, smtp_status = handle_forward(
  779. envelope, smtp, msg, rcpt_to
  780. )
  781. res.append((is_delivered, smtp_status))
  782. # special handling for self-forwarding
  783. # just consider success delivery in this case
  784. if len(res) == 1 and res[0][1] == _SELF_FORWARDING_STATUS:
  785. LOG.d("Self-forwarding, ignore")
  786. return "250 SL OK"
  787. for (is_success, smtp_status) in res:
  788. # Consider all deliveries successful if 1 delivery is successful
  789. if is_success:
  790. return smtp_status
  791. # Failed delivery for all, return the first failure
  792. return res[0][1]
  793. if __name__ == "__main__":
  794. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  795. controller.start()
  796. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  797. while True:
  798. time.sleep(2)