email_handler.py 27 KB

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