email_handler.py 25 KB

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