email_handler.py 27 KB

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