email_handler.py 28 KB

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