email_handler.py 27 KB

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