email_handler.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  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 asyncio
  28. import email
  29. import os
  30. import time
  31. import uuid
  32. from email import encoders
  33. from email.message import Message
  34. from email.mime.application import MIMEApplication
  35. from email.mime.multipart import MIMEMultipart
  36. from email.utils import parseaddr, formataddr, make_msgid
  37. from io import BytesIO
  38. from smtplib import SMTP
  39. from typing import List, Tuple
  40. import aiosmtpd
  41. import aiospamc
  42. import arrow
  43. import spf
  44. from aiosmtpd.smtp import Envelope
  45. from app import pgp_utils, s3
  46. from app.alias_utils import try_auto_create
  47. from app.config import (
  48. EMAIL_DOMAIN,
  49. POSTFIX_SERVER,
  50. URL,
  51. ALIAS_DOMAINS,
  52. POSTFIX_SUBMISSION_TLS,
  53. UNSUBSCRIBER,
  54. LOAD_PGP_EMAIL_HANDLER,
  55. ENFORCE_SPF,
  56. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  57. ALERT_BOUNCE_EMAIL,
  58. ALERT_SPAM_EMAIL,
  59. ALERT_SPF,
  60. POSTFIX_PORT,
  61. SENDER,
  62. SENDER_DIR,
  63. SPAMASSASSIN_HOST,
  64. MAX_SPAM_SCORE,
  65. MAX_REPLY_PHASE_SPAM_SCORE,
  66. )
  67. from app.email_utils import (
  68. send_email,
  69. add_dkim_signature,
  70. add_or_replace_header,
  71. delete_header,
  72. email_belongs_to_alias_domains,
  73. render,
  74. get_orig_message_from_bounce,
  75. delete_all_headers_except,
  76. get_addrs_from_header,
  77. get_spam_info,
  78. get_orig_message_from_spamassassin_report,
  79. parseaddr_unicode,
  80. send_email_with_rate_control,
  81. get_email_domain_part,
  82. copy,
  83. to_bytes,
  84. get_header_from_bounce,
  85. )
  86. from app.extensions import db
  87. from app.greylisting import greylisting_needed
  88. from app.log import LOG
  89. from app.models import (
  90. Alias,
  91. Contact,
  92. EmailLog,
  93. CustomDomain,
  94. User,
  95. RefusedEmail,
  96. Mailbox,
  97. )
  98. from app.pgp_utils import PGPException
  99. from app.utils import random_string
  100. from init_app import load_pgp_public_keys
  101. from server import create_app, create_light_app
  102. # forward or reply
  103. _DIRECTION = "X-SimpleLogin-Type"
  104. _IP_HEADER = "X-SimpleLogin-Client-IP"
  105. _MAILBOX_ID_HEADER = "X-SimpleLogin-Mailbox-ID"
  106. _EMAIL_LOG_ID_HEADER = "X-SimpleLogin-EmailLog-ID"
  107. _MESSAGE_ID = "Message-ID"
  108. # fix the database connection leak issue
  109. # use this method instead of create_app
  110. def new_app():
  111. app = create_light_app()
  112. @app.teardown_appcontext
  113. def shutdown_session(response_or_exc):
  114. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  115. db.session.remove()
  116. # dispose the engine too
  117. db.engine.dispose()
  118. return app
  119. def get_or_create_contact(
  120. contact_from_header: str, mail_from: str, alias: Alias
  121. ) -> Contact:
  122. """
  123. contact_from_header is the RFC 2047 format FROM header
  124. """
  125. # contact_from_header can be None, use mail_from in this case instead
  126. contact_from_header = contact_from_header or mail_from
  127. # force convert header to string, sometimes contact_from_header is Header object
  128. contact_from_header = str(contact_from_header)
  129. contact_name, contact_email = parseaddr_unicode(contact_from_header)
  130. if not contact_email:
  131. # From header is wrongly formatted, try with mail_from
  132. LOG.warning("From header is empty, parse mail_from %s %s", mail_from, alias)
  133. contact_name, contact_email = parseaddr_unicode(mail_from)
  134. if not contact_email:
  135. LOG.exception(
  136. "Cannot parse contact from from_header:%s, mail_from:%s",
  137. contact_from_header,
  138. mail_from,
  139. )
  140. contact = Contact.get_by(alias_id=alias.id, website_email=contact_email)
  141. if contact:
  142. if contact.name != contact_name:
  143. LOG.d(
  144. "Update contact %s name %s to %s", contact, contact.name, contact_name,
  145. )
  146. contact.name = contact_name
  147. db.session.commit()
  148. else:
  149. LOG.debug(
  150. "create contact for alias %s and contact %s", alias, contact_from_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. )
  160. db.session.commit()
  161. return contact
  162. def replace_header_when_forward(msg: Message, alias: Alias, header: str):
  163. """
  164. Replace CC or To header by Reply emails in forward phase
  165. """
  166. addrs = get_addrs_from_header(msg, header)
  167. # Nothing to do
  168. if not addrs:
  169. return
  170. new_addrs: [str] = []
  171. for addr in addrs:
  172. contact_name, contact_email = parseaddr_unicode(addr)
  173. # no transformation when alias is already in the header
  174. if contact_email == alias.email:
  175. new_addrs.append(addr)
  176. continue
  177. contact = Contact.get_by(alias_id=alias.id, website_email=contact_email)
  178. if contact:
  179. # update the contact name if needed
  180. if contact.name != contact_name:
  181. LOG.d(
  182. "Update contact %s name %s to %s",
  183. contact,
  184. contact.name,
  185. contact_name,
  186. )
  187. contact.name = contact_name
  188. db.session.commit()
  189. else:
  190. LOG.debug(
  191. "create contact for alias %s and email %s, header %s",
  192. alias,
  193. contact_email,
  194. header,
  195. )
  196. reply_email = generate_reply_email()
  197. contact = Contact.create(
  198. user_id=alias.user_id,
  199. alias_id=alias.id,
  200. website_email=contact_email,
  201. name=contact_name,
  202. reply_email=reply_email,
  203. is_cc=header.lower() == "cc",
  204. )
  205. db.session.commit()
  206. new_addrs.append(contact.new_addr())
  207. if new_addrs:
  208. new_header = ",".join(new_addrs)
  209. LOG.d("Replace %s header, old: %s, new: %s", header, msg[header], new_header)
  210. add_or_replace_header(msg, header, new_header)
  211. else:
  212. LOG.d("Delete %s header, old value %s", header, msg[header])
  213. delete_header(msg, header)
  214. def replace_header_when_reply(msg: Message, alias: Alias, header: str):
  215. """
  216. Replace CC or To Reply emails by original emails
  217. """
  218. addrs = get_addrs_from_header(msg, header)
  219. # Nothing to do
  220. if not addrs:
  221. return
  222. new_addrs: [str] = []
  223. for addr in addrs:
  224. name, reply_email = parseaddr(addr)
  225. # no transformation when alias is already in the header
  226. if reply_email == alias.email:
  227. continue
  228. contact = Contact.get_by(reply_email=reply_email)
  229. if not contact:
  230. LOG.warning(
  231. "%s email in reply phase %s must be reply emails", header, reply_email
  232. )
  233. # still keep this email in header
  234. new_addrs.append(addr)
  235. else:
  236. new_addrs.append(formataddr((contact.name, contact.website_email)))
  237. if new_addrs:
  238. new_header = ",".join(new_addrs)
  239. LOG.d("Replace %s header, old: %s, new: %s", header, msg[header], new_header)
  240. add_or_replace_header(msg, header, new_header)
  241. else:
  242. LOG.d("delete the %s header. Old value %s", header, msg[header])
  243. delete_header(msg, header)
  244. def replace_str_in_msg(msg: Message, fr: str, to: str):
  245. if msg.get_content_maintype() != "text":
  246. return msg
  247. new_body = msg.get_payload(decode=True).replace(fr.encode(), to.encode())
  248. # If utf-8 decoding fails, do not touch message part
  249. try:
  250. new_body = new_body.decode("utf-8")
  251. except:
  252. return msg
  253. cte = (
  254. msg["Content-Transfer-Encoding"].lower()
  255. if msg["Content-Transfer-Encoding"]
  256. else None
  257. )
  258. subtype = msg.get_content_subtype()
  259. delete_header(msg, "Content-Transfer-Encoding")
  260. delete_header(msg, "Content-Type")
  261. email.contentmanager.set_text_content(msg, new_body, subtype=subtype, cte=cte)
  262. return msg
  263. def generate_reply_email():
  264. # generate a reply_email, make sure it is unique
  265. # not use while loop to avoid infinite loop
  266. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  267. for _ in range(1000):
  268. if not Contact.get_by(reply_email=reply_email):
  269. # found!
  270. break
  271. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  272. return reply_email
  273. def should_append_alias(msg: Message, address: str):
  274. """whether an alias should be appended to TO header in message"""
  275. # # force convert header to string, sometimes addrs is Header object
  276. if msg["To"] and address.lower() in str(msg["To"]).lower():
  277. return False
  278. if msg["Cc"] and address.lower() in str(msg["Cc"]).lower():
  279. return False
  280. return True
  281. _MIME_HEADERS = [
  282. "MIME-Version",
  283. "Content-Type",
  284. "Content-Disposition",
  285. "Content-Transfer-Encoding",
  286. ]
  287. _MIME_HEADERS = [h.lower() for h in _MIME_HEADERS]
  288. def prepare_pgp_message(orig_msg: Message, pgp_fingerprint: str):
  289. msg = MIMEMultipart("encrypted", protocol="application/pgp-encrypted")
  290. # copy all headers from original message except all standard MIME headers
  291. for i in reversed(range(len(orig_msg._headers))):
  292. header_name = orig_msg._headers[i][0].lower()
  293. if header_name.lower() not in _MIME_HEADERS:
  294. msg[header_name] = orig_msg._headers[i][1]
  295. # Delete unnecessary headers in orig_msg except to save space
  296. delete_all_headers_except(
  297. orig_msg, _MIME_HEADERS,
  298. )
  299. first = MIMEApplication(
  300. _subtype="pgp-encrypted", _encoder=encoders.encode_7or8bit, _data=""
  301. )
  302. first.set_payload("Version: 1")
  303. msg.attach(first)
  304. second = MIMEApplication("octet-stream", _encoder=encoders.encode_7or8bit)
  305. second.add_header("Content-Disposition", "inline")
  306. # encrypt original message
  307. encrypted_data = pgp_utils.encrypt_file(
  308. BytesIO(orig_msg.as_bytes()), pgp_fingerprint
  309. )
  310. second.set_payload(encrypted_data)
  311. msg.attach(second)
  312. return msg
  313. async def handle_forward(
  314. envelope, smtp: SMTP, msg: Message, rcpt_to: str
  315. ) -> List[Tuple[bool, str]]:
  316. """return whether an email has been delivered and
  317. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  318. """
  319. address = rcpt_to.lower().strip() # alias@SL
  320. alias = Alias.get_by(email=address)
  321. if not alias:
  322. LOG.d("alias %s not exist. Try to see if it can be created on the fly", address)
  323. alias = try_auto_create(address)
  324. if not alias:
  325. LOG.d("alias %s cannot be created on-the-fly, return 550", address)
  326. return [(False, "550 SL E3 Email not exist")]
  327. contact = get_or_create_contact(msg["From"], envelope.mail_from, alias)
  328. email_log = EmailLog.create(contact_id=contact.id, user_id=contact.user_id)
  329. db.session.commit()
  330. if not alias.enabled:
  331. LOG.d("%s is disabled, do not forward", alias)
  332. email_log.blocked = True
  333. db.session.commit()
  334. # do not return 5** to allow user to receive emails later when alias is enabled
  335. return [(True, "250 Message accepted for delivery")]
  336. user = alias.user
  337. ret = []
  338. mailboxes = alias.mailboxes
  339. # no need to create a copy of message
  340. if len(mailboxes) == 1:
  341. mailbox = mailboxes[0]
  342. ret.append(
  343. await forward_email_to_mailbox(
  344. alias, msg, email_log, contact, envelope, smtp, mailbox, user
  345. )
  346. )
  347. # create a copy of message for each forward
  348. else:
  349. for mailbox in mailboxes:
  350. ret.append(
  351. await forward_email_to_mailbox(
  352. alias, copy(msg), email_log, contact, envelope, smtp, mailbox, user
  353. )
  354. )
  355. return ret
  356. async def forward_email_to_mailbox(
  357. alias,
  358. msg: Message,
  359. email_log: EmailLog,
  360. contact: Contact,
  361. envelope,
  362. smtp: SMTP,
  363. mailbox,
  364. user,
  365. ) -> (bool, str):
  366. LOG.d("Forward %s -> %s -> %s", contact, alias, mailbox)
  367. # sanity check: make sure mailbox is not actually an alias
  368. if get_email_domain_part(alias.email) == get_email_domain_part(mailbox.email):
  369. LOG.exception(
  370. "Mailbox has the same domain as alias. %s -> %s -> %s",
  371. contact,
  372. alias,
  373. mailbox,
  374. )
  375. return False, "550 SL E14"
  376. # Spam check
  377. spam_status = ""
  378. is_spam = False
  379. if SPAMASSASSIN_HOST:
  380. start = time.time()
  381. spam_score = await get_spam_score(msg)
  382. LOG.d(
  383. "%s -> %s - spam score %s in %s seconds",
  384. contact,
  385. alias,
  386. spam_score,
  387. time.time() - start,
  388. )
  389. email_log.spam_score = spam_score
  390. db.session.commit()
  391. if (user.max_spam_score and spam_score > user.max_spam_score) or (
  392. not user.max_spam_score and spam_score > MAX_SPAM_SCORE
  393. ):
  394. is_spam = True
  395. spam_status = "Spam detected by SpamAssassin server"
  396. else:
  397. is_spam, spam_status = get_spam_info(msg, max_score=user.max_spam_score)
  398. if is_spam:
  399. LOG.warning("Email detected as spam. Alias: %s, from: %s", alias, contact)
  400. email_log.is_spam = True
  401. email_log.spam_status = spam_status
  402. db.session.commit()
  403. handle_spam(contact, alias, msg, user, mailbox, email_log)
  404. return False, "550 SL E1 Email detected as spam"
  405. # create PGP email if needed
  406. if mailbox.pgp_finger_print and user.is_premium() and not alias.disable_pgp:
  407. LOG.d("Encrypt message using mailbox %s", mailbox)
  408. try:
  409. msg = prepare_pgp_message(msg, mailbox.pgp_finger_print)
  410. except PGPException:
  411. LOG.exception(
  412. "Cannot encrypt message %s -> %s. %s %s", contact, alias, mailbox, user
  413. )
  414. # so the client can retry later
  415. return False, "421 SL E12 Retry later"
  416. # add custom header
  417. add_or_replace_header(msg, _DIRECTION, "Forward")
  418. # remove reply-to & sender header if present
  419. delete_header(msg, "Reply-To")
  420. delete_header(msg, "Sender")
  421. delete_header(msg, _IP_HEADER)
  422. add_or_replace_header(msg, _MAILBOX_ID_HEADER, str(mailbox.id))
  423. add_or_replace_header(msg, _EMAIL_LOG_ID_HEADER, str(email_log.id))
  424. add_or_replace_header(msg, _MESSAGE_ID, make_msgid(str(email_log.id), EMAIL_DOMAIN))
  425. # change the from header so the sender comes from @SL
  426. # so it can pass DMARC check
  427. # replace the email part in from: header
  428. contact_from_header = msg["From"]
  429. new_from_header = contact.new_addr()
  430. add_or_replace_header(msg, "From", new_from_header)
  431. LOG.d("new_from_header:%s, old header %s", new_from_header, contact_from_header)
  432. # replace CC & To emails by reply-email for all emails that are not alias
  433. replace_header_when_forward(msg, alias, "Cc")
  434. replace_header_when_forward(msg, alias, "To")
  435. # append alias into the TO header if it's not present in To or CC
  436. if should_append_alias(msg, alias.email):
  437. LOG.d("append alias %s to TO header %s", alias, msg["To"])
  438. if msg["To"]:
  439. to_header = msg["To"] + "," + alias.email
  440. else:
  441. to_header = alias.email
  442. add_or_replace_header(msg, "To", to_header.strip())
  443. # add List-Unsubscribe header
  444. if UNSUBSCRIBER:
  445. unsubscribe_link = f"mailto:{UNSUBSCRIBER}?subject={alias.id}="
  446. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  447. else:
  448. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  449. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  450. add_or_replace_header(
  451. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  452. )
  453. add_dkim_signature(msg, EMAIL_DOMAIN)
  454. LOG.d(
  455. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  456. contact.website_email,
  457. mailbox.email,
  458. envelope.mail_options,
  459. envelope.rcpt_options,
  460. )
  461. # smtp.send_message has UnicodeEncodeErroremail issue
  462. # encode message raw directly instead
  463. smtp.sendmail(
  464. contact.reply_email,
  465. mailbox.email,
  466. msg.as_bytes(),
  467. envelope.mail_options,
  468. envelope.rcpt_options,
  469. )
  470. db.session.commit()
  471. return True, "250 Message accepted for delivery"
  472. async def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> (bool, str):
  473. """
  474. return whether an email has been delivered and
  475. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  476. """
  477. reply_email = rcpt_to.lower().strip()
  478. # reply_email must end with EMAIL_DOMAIN
  479. if not reply_email.endswith(EMAIL_DOMAIN):
  480. LOG.warning(f"Reply email {reply_email} has wrong domain")
  481. return False, "550 SL E2"
  482. contact = Contact.get_by(reply_email=reply_email)
  483. if not contact:
  484. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  485. return False, "550 SL E4 Email not exist"
  486. alias = contact.alias
  487. address: str = contact.alias.email
  488. alias_domain = address[address.find("@") + 1 :]
  489. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  490. if not email_belongs_to_alias_domains(alias.email):
  491. if not CustomDomain.get_by(domain=alias_domain):
  492. return False, "550 SL E5"
  493. user = alias.user
  494. mail_from = envelope.mail_from.lower().strip()
  495. # bounce email initiated by Postfix
  496. # can happen in case emails cannot be delivered to user-email
  497. # in this case Postfix will try to send a bounce report to original sender, which is
  498. # the "reply email"
  499. if mail_from == "<>":
  500. LOG.warning(
  501. "Bounce when sending to alias %s from %s, user %s", alias, contact, user,
  502. )
  503. handle_bounce(contact, alias, msg, user)
  504. return False, "550 SL E6"
  505. mailbox = Mailbox.get_by(email=mail_from, user_id=user.id)
  506. if not mailbox or mailbox not in alias.mailboxes:
  507. # only mailbox can send email to the reply-email
  508. handle_unknown_mailbox(envelope, msg, reply_email, user, alias)
  509. return False, "550 SL E7"
  510. if ENFORCE_SPF and mailbox.force_spf:
  511. ip = msg[_IP_HEADER]
  512. if not spf_pass(ip, envelope, mailbox, user, alias, contact.website_email, msg):
  513. # cannot use 4** here as sender will retry. 5** because that generates bounce report
  514. return True, "250 SL E11"
  515. email_log = EmailLog.create(
  516. contact_id=contact.id, is_reply=True, user_id=contact.user_id
  517. )
  518. # Spam check
  519. spam_status = ""
  520. is_spam = False
  521. # do not use user.max_spam_score here
  522. if SPAMASSASSIN_HOST:
  523. start = time.time()
  524. spam_score = await get_spam_score(msg)
  525. LOG.d(
  526. "%s -> %s - spam score %s in %s seconds",
  527. alias,
  528. contact,
  529. spam_score,
  530. time.time() - start,
  531. )
  532. email_log.spam_score = spam_score
  533. if spam_score > MAX_REPLY_PHASE_SPAM_SCORE:
  534. is_spam = True
  535. spam_status = "Spam detected by SpamAssassin server"
  536. else:
  537. is_spam, spam_status = get_spam_info(msg, max_score=MAX_REPLY_PHASE_SPAM_SCORE)
  538. if is_spam:
  539. LOG.exception(
  540. "Reply phase - email sent from %s to %s detected as spam", alias, contact
  541. )
  542. email_log.is_spam = True
  543. email_log.spam_status = spam_status
  544. db.session.commit()
  545. handle_spam(contact, alias, msg, user, mailbox, email_log, is_reply=True)
  546. return False, "550 SL E15 Email detected as spam"
  547. delete_header(msg, _IP_HEADER)
  548. delete_header(msg, "DKIM-Signature")
  549. delete_header(msg, "Received")
  550. # make the email comes from alias
  551. from_header = alias.email
  552. # add alias name from alias
  553. if alias.name:
  554. LOG.d("Put alias name in from header")
  555. from_header = formataddr((alias.name, alias.email))
  556. elif alias.custom_domain:
  557. LOG.d("Put domain default alias name in from header")
  558. # add alias name from domain
  559. if alias.custom_domain.name:
  560. from_header = formataddr((alias.custom_domain.name, alias.email))
  561. add_or_replace_header(msg, "From", from_header)
  562. # some email providers like ProtonMail adds automatically the Reply-To field
  563. # make sure to delete it
  564. delete_header(msg, "Reply-To")
  565. # remove sender header if present as this could reveal user real email
  566. delete_header(msg, "Sender")
  567. delete_header(msg, "X-Sender")
  568. replace_header_when_reply(msg, alias, "To")
  569. replace_header_when_reply(msg, alias, "Cc")
  570. add_or_replace_header(
  571. msg,
  572. _MESSAGE_ID,
  573. make_msgid(str(email_log.id), get_email_domain_part(alias.email)),
  574. )
  575. add_or_replace_header(msg, _EMAIL_LOG_ID_HEADER, str(email_log.id))
  576. add_or_replace_header(msg, _DIRECTION, "Reply")
  577. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  578. delete_header(msg, "Received-SPF")
  579. LOG.d(
  580. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  581. alias.email,
  582. contact.website_email,
  583. envelope.mail_options,
  584. envelope.rcpt_options,
  585. )
  586. # replace "ra+string@simplelogin.co" by the contact email in the email body
  587. # as this is usually included when replying
  588. if user.replace_reverse_alias:
  589. if msg.is_multipart():
  590. for part in msg.walk():
  591. if part.get_content_maintype() != "text":
  592. continue
  593. part = replace_str_in_msg(part, reply_email, contact.website_email)
  594. else:
  595. msg = replace_str_in_msg(msg, reply_email, contact.website_email)
  596. if alias_domain in ALIAS_DOMAINS:
  597. add_dkim_signature(msg, alias_domain)
  598. # add DKIM-Signature for custom-domain alias
  599. else:
  600. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  601. if custom_domain.dkim_verified:
  602. add_dkim_signature(msg, alias_domain)
  603. # create PGP email if needed
  604. if contact.pgp_finger_print and user.is_premium():
  605. LOG.d("Encrypt message for contact %s", contact)
  606. try:
  607. msg = prepare_pgp_message(msg, contact.pgp_finger_print)
  608. except PGPException:
  609. LOG.exception(
  610. "Cannot encrypt message %s -> %s. %s %s", alias, contact, mailbox, user
  611. )
  612. # to not save the email_log
  613. db.session.rollback()
  614. # return 421 so the client can retry later
  615. return False, "421 SL E13 Retry later"
  616. try:
  617. smtp.sendmail(
  618. alias.email,
  619. contact.website_email,
  620. msg.as_bytes(),
  621. envelope.mail_options,
  622. envelope.rcpt_options,
  623. )
  624. except Exception:
  625. # to not save the email_log
  626. db.session.rollback()
  627. LOG.exception("Cannot send email from %s to %s", alias, contact)
  628. send_email(
  629. mailbox.email,
  630. f"Email cannot be sent to {contact.email} from {alias.email}",
  631. render(
  632. "transactional/reply-error.txt",
  633. user=user,
  634. alias=alias,
  635. contact=contact,
  636. contact_domain=get_email_domain_part(contact.email),
  637. ),
  638. render(
  639. "transactional/reply-error.html",
  640. user=user,
  641. alias=alias,
  642. contact=contact,
  643. contact_domain=get_email_domain_part(contact.email),
  644. ),
  645. )
  646. db.session.commit()
  647. return True, "250 Message accepted for delivery"
  648. def spf_pass(
  649. ip: str,
  650. envelope,
  651. mailbox: Mailbox,
  652. user: User,
  653. alias: Alias,
  654. contact_email: str,
  655. msg: Message,
  656. ) -> bool:
  657. if ip:
  658. LOG.d("Enforce SPF")
  659. try:
  660. r = spf.check2(i=ip, s=envelope.mail_from.lower(), h=None)
  661. except Exception:
  662. LOG.exception("SPF error, mailbox %s, ip %s", mailbox.email, ip)
  663. else:
  664. # TODO: Handle temperr case (e.g. dns timeout)
  665. # only an absolute pass, or no SPF policy at all is 'valid'
  666. if r[0] not in ["pass", "none"]:
  667. LOG.warning(
  668. "SPF fail for mailbox %s, reason %s, failed IP %s",
  669. mailbox.email,
  670. r[0],
  671. ip,
  672. )
  673. send_email_with_rate_control(
  674. user,
  675. ALERT_SPF,
  676. mailbox.email,
  677. f"SimpleLogin Alert: attempt to send emails from your alias {alias.email} from unknown IP Address",
  678. render(
  679. "transactional/spf-fail.txt",
  680. name=user.name,
  681. alias=alias.email,
  682. ip=ip,
  683. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  684. to_email=contact_email,
  685. subject=msg["Subject"],
  686. time=arrow.now(),
  687. ),
  688. render(
  689. "transactional/spf-fail.html",
  690. name=user.name,
  691. alias=alias.email,
  692. ip=ip,
  693. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  694. to_email=contact_email,
  695. subject=msg["Subject"],
  696. time=arrow.now(),
  697. ),
  698. )
  699. return False
  700. else:
  701. LOG.warning(
  702. "Could not find %s header %s -> %s",
  703. _IP_HEADER,
  704. mailbox.email,
  705. contact_email,
  706. )
  707. return True
  708. def handle_unknown_mailbox(envelope, msg, reply_email: str, user: User, alias: Alias):
  709. LOG.warning(
  710. f"Reply email can only be used by mailbox. "
  711. f"Actual mail_from: %s. msg from header: %s, reverse-alias %s, %s %s",
  712. envelope.mail_from,
  713. msg["From"],
  714. reply_email,
  715. alias,
  716. user,
  717. )
  718. send_email_with_rate_control(
  719. user,
  720. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  721. user.email,
  722. f"Reply from your alias {alias.email} only works from your mailbox",
  723. render(
  724. "transactional/reply-must-use-personal-email.txt",
  725. name=user.name,
  726. alias=alias,
  727. sender=envelope.mail_from,
  728. ),
  729. render(
  730. "transactional/reply-must-use-personal-email.html",
  731. name=user.name,
  732. alias=alias,
  733. sender=envelope.mail_from,
  734. ),
  735. )
  736. # Notify sender that they cannot send emails to this address
  737. send_email_with_rate_control(
  738. user,
  739. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  740. envelope.mail_from,
  741. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  742. render(
  743. "transactional/send-from-alias-from-unknown-sender.txt",
  744. sender=envelope.mail_from,
  745. reply_email=reply_email,
  746. ),
  747. render(
  748. "transactional/send-from-alias-from-unknown-sender.html",
  749. sender=envelope.mail_from,
  750. reply_email=reply_email,
  751. ),
  752. )
  753. def handle_bounce(contact: Contact, alias: Alias, msg: Message, user: User):
  754. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  755. # Store the bounced email
  756. # generate a name for the email
  757. random_name = str(uuid.uuid4())
  758. full_report_path = f"refused-emails/full-{random_name}.eml"
  759. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  760. file_path = None
  761. mailbox = None
  762. email_log: EmailLog = None
  763. orig_msg = get_orig_message_from_bounce(msg)
  764. if not orig_msg:
  765. # Some MTA does not return the original message in bounce message
  766. # nothing we can do here
  767. LOG.warning(
  768. "Cannot parse original message from bounce message %s %s %s %s",
  769. alias,
  770. user,
  771. contact,
  772. full_report_path,
  773. )
  774. else:
  775. file_path = f"refused-emails/{random_name}.eml"
  776. s3.upload_email_from_bytesio(
  777. file_path, BytesIO(orig_msg.as_bytes()), random_name
  778. )
  779. try:
  780. mailbox_id = int(orig_msg[_MAILBOX_ID_HEADER])
  781. except TypeError:
  782. LOG.exception(
  783. "cannot parse mailbox from original message header %s",
  784. orig_msg[_MAILBOX_ID_HEADER],
  785. )
  786. else:
  787. mailbox = Mailbox.get(mailbox_id)
  788. if not mailbox or mailbox.user_id != user.id:
  789. LOG.exception(
  790. "Tampered message mailbox_id %s, %s, %s, %s %s",
  791. mailbox_id,
  792. user,
  793. alias,
  794. contact,
  795. full_report_path,
  796. )
  797. # cannot use this tampered mailbox, reset it
  798. mailbox = None
  799. # try to get the original email_log
  800. try:
  801. email_log_id = int(orig_msg[_EMAIL_LOG_ID_HEADER])
  802. except TypeError:
  803. LOG.exception(
  804. "cannot parse email log from original message header %s",
  805. orig_msg[_EMAIL_LOG_ID_HEADER],
  806. )
  807. else:
  808. email_log = EmailLog.get(email_log_id)
  809. refused_email = RefusedEmail.create(
  810. path=file_path, full_report_path=full_report_path, user_id=user.id
  811. )
  812. db.session.flush()
  813. LOG.d("Create refused email %s", refused_email)
  814. if not mailbox:
  815. LOG.debug("Try to get mailbox from bounce report")
  816. try:
  817. mailbox_id = int(get_header_from_bounce(msg, _MAILBOX_ID_HEADER))
  818. except Exception:
  819. LOG.exception("cannot get mailbox-id from bounce report, %s", refused_email)
  820. else:
  821. mailbox = Mailbox.get(mailbox_id)
  822. if not mailbox or mailbox.user_id != user.id:
  823. LOG.exception(
  824. "Tampered message mailbox_id %s, %s, %s, %s %s",
  825. mailbox_id,
  826. user,
  827. alias,
  828. contact,
  829. full_report_path,
  830. )
  831. mailbox = None
  832. if not email_log:
  833. LOG.d("Try to get email log from bounce report")
  834. try:
  835. email_log_id = int(get_header_from_bounce(msg, _EMAIL_LOG_ID_HEADER))
  836. except Exception:
  837. LOG.exception(
  838. "cannot get email log id from bounce report, %s", refused_email
  839. )
  840. else:
  841. email_log = EmailLog.get(email_log_id)
  842. # use the default mailbox as the last option
  843. if not mailbox:
  844. LOG.warning("Use %s default mailbox %s", alias, refused_email)
  845. mailbox = alias.mailbox
  846. # create a new email log as the last option
  847. if not email_log:
  848. LOG.warning("cannot get the original email_log, create a new one")
  849. email_log: EmailLog = EmailLog.create(
  850. contact_id=contact.id, user_id=contact.user_id
  851. )
  852. email_log.bounced = True
  853. email_log.refused_email_id = refused_email.id
  854. email_log.bounced_mailbox_id = mailbox.id
  855. db.session.commit()
  856. refused_email_url = (
  857. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  858. )
  859. nb_bounced = EmailLog.filter_by(contact_id=contact.id, bounced=True).count()
  860. if nb_bounced >= 2 and alias.cannot_be_disabled:
  861. LOG.warning("%s cannot be disabled", alias)
  862. # inform user if this is the first bounced email
  863. if nb_bounced == 1 or (nb_bounced >= 2 and alias.cannot_be_disabled):
  864. LOG.d(
  865. "Inform user %s about bounced email sent by %s to alias %s",
  866. user,
  867. contact.website_email,
  868. alias,
  869. )
  870. send_email_with_rate_control(
  871. user,
  872. ALERT_BOUNCE_EMAIL,
  873. user.email,
  874. f"Email from {contact.website_email} to {alias.email} cannot be delivered to your inbox",
  875. render(
  876. "transactional/bounced-email.txt",
  877. name=user.name,
  878. alias=alias,
  879. website_email=contact.website_email,
  880. disable_alias_link=disable_alias_link,
  881. refused_email_url=refused_email_url,
  882. mailbox_email=mailbox.email,
  883. ),
  884. render(
  885. "transactional/bounced-email.html",
  886. name=user.name,
  887. alias=alias,
  888. website_email=contact.website_email,
  889. disable_alias_link=disable_alias_link,
  890. refused_email_url=refused_email_url,
  891. mailbox_email=mailbox.email,
  892. ),
  893. )
  894. # disable the alias the second time email is bounced
  895. elif nb_bounced >= 2:
  896. LOG.d(
  897. "Bounce happens again with alias %s from %s. Disable alias now ",
  898. alias,
  899. contact.website_email,
  900. )
  901. alias.enabled = False
  902. db.session.commit()
  903. send_email_with_rate_control(
  904. user,
  905. ALERT_BOUNCE_EMAIL,
  906. user.email,
  907. f"Alias {alias.email} has been disabled due to second undelivered email from {contact.website_email}",
  908. render(
  909. "transactional/automatic-disable-alias.txt",
  910. name=user.name,
  911. alias=alias,
  912. website_email=contact.website_email,
  913. refused_email_url=refused_email_url,
  914. mailbox_email=mailbox.email,
  915. ),
  916. render(
  917. "transactional/automatic-disable-alias.html",
  918. name=user.name,
  919. alias=alias,
  920. website_email=contact.website_email,
  921. refused_email_url=refused_email_url,
  922. mailbox_email=mailbox.email,
  923. ),
  924. )
  925. def handle_spam(
  926. contact: Contact,
  927. alias: Alias,
  928. msg: Message,
  929. user: User,
  930. mailbox: Mailbox,
  931. email_log: EmailLog,
  932. is_reply=False, # whether the email is in forward or reply phase
  933. ):
  934. # Store the report & original email
  935. orig_msg = get_orig_message_from_spamassassin_report(msg)
  936. # generate a name for the email
  937. random_name = str(uuid.uuid4())
  938. full_report_path = f"spams/full-{random_name}.eml"
  939. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  940. file_path = None
  941. if orig_msg:
  942. file_path = f"spams/{random_name}.eml"
  943. s3.upload_email_from_bytesio(
  944. file_path, BytesIO(orig_msg.as_bytes()), random_name
  945. )
  946. refused_email = RefusedEmail.create(
  947. path=file_path, full_report_path=full_report_path, user_id=user.id
  948. )
  949. db.session.flush()
  950. email_log.refused_email_id = refused_email.id
  951. db.session.commit()
  952. LOG.d("Create spam email %s", refused_email)
  953. refused_email_url = (
  954. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  955. )
  956. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  957. if is_reply:
  958. LOG.d(
  959. "Inform %s (%s) about spam email sent from alias %s to %s",
  960. mailbox,
  961. user,
  962. alias,
  963. contact,
  964. )
  965. send_email_with_rate_control(
  966. user,
  967. ALERT_SPAM_EMAIL,
  968. mailbox.email,
  969. f"Email from {contact.website_email} to {alias.email} is detected as spam",
  970. render(
  971. "transactional/spam-email-reply-phase.txt",
  972. name=user.name,
  973. alias=alias,
  974. website_email=contact.website_email,
  975. disable_alias_link=disable_alias_link,
  976. refused_email_url=refused_email_url,
  977. ),
  978. render(
  979. "transactional/spam-email-reply-phase.html",
  980. name=user.name,
  981. alias=alias,
  982. website_email=contact.website_email,
  983. disable_alias_link=disable_alias_link,
  984. refused_email_url=refused_email_url,
  985. ),
  986. )
  987. else:
  988. # inform user
  989. LOG.d(
  990. "Inform %s (%s) about spam email sent by %s to alias %s",
  991. mailbox,
  992. user,
  993. contact,
  994. alias,
  995. )
  996. send_email_with_rate_control(
  997. user,
  998. ALERT_SPAM_EMAIL,
  999. mailbox.email,
  1000. f"Email from {contact.website_email} to {alias.email} is detected as spam",
  1001. render(
  1002. "transactional/spam-email.txt",
  1003. name=user.name,
  1004. alias=alias,
  1005. website_email=contact.website_email,
  1006. disable_alias_link=disable_alias_link,
  1007. refused_email_url=refused_email_url,
  1008. ),
  1009. render(
  1010. "transactional/spam-email.html",
  1011. name=user.name,
  1012. alias=alias,
  1013. website_email=contact.website_email,
  1014. disable_alias_link=disable_alias_link,
  1015. refused_email_url=refused_email_url,
  1016. ),
  1017. )
  1018. def handle_unsubscribe(envelope: Envelope):
  1019. msg = email.message_from_bytes(envelope.original_content)
  1020. # format: alias_id:
  1021. subject = msg["Subject"]
  1022. try:
  1023. # subject has the format {alias.id}=
  1024. if subject.endswith("="):
  1025. alias_id = int(subject[:-1])
  1026. # some email providers might strip off the = suffix
  1027. else:
  1028. alias_id = int(subject)
  1029. alias = Alias.get(alias_id)
  1030. except Exception:
  1031. LOG.warning("Cannot parse alias from subject %s", msg["Subject"])
  1032. return "550 SL E8 Wrongly formatted subject"
  1033. if not alias:
  1034. LOG.warning("No such alias %s", alias_id)
  1035. return "550 SL E9 Email not exist"
  1036. # This sender cannot unsubscribe
  1037. mail_from = envelope.mail_from.lower().strip()
  1038. mailbox = Mailbox.get_by(user_id=alias.user_id, email=mail_from)
  1039. if not mailbox or mailbox not in alias.mailboxes:
  1040. LOG.d("%s cannot disable alias %s", envelope.mail_from, alias)
  1041. return "550 SL E10 unauthorized"
  1042. # Sender is owner of this alias
  1043. alias.enabled = False
  1044. db.session.commit()
  1045. user = alias.user
  1046. enable_alias_url = URL + f"/dashboard/?highlight_alias_id={alias.id}"
  1047. for mailbox in alias.mailboxes:
  1048. send_email(
  1049. mailbox.email,
  1050. f"Alias {alias.email} has been disabled successfully",
  1051. render(
  1052. "transactional/unsubscribe-disable-alias.txt",
  1053. user=user,
  1054. alias=alias.email,
  1055. enable_alias_url=enable_alias_url,
  1056. ),
  1057. render(
  1058. "transactional/unsubscribe-disable-alias.html",
  1059. user=user,
  1060. alias=alias.email,
  1061. enable_alias_url=enable_alias_url,
  1062. ),
  1063. )
  1064. return "250 Unsubscribe request accepted"
  1065. def handle_sender_email(envelope: Envelope):
  1066. filename = (
  1067. arrow.now().format("YYYY-MM-DD_HH-mm-ss") + "_" + random_string(10) + ".eml"
  1068. )
  1069. filepath = os.path.join(SENDER_DIR, filename)
  1070. with open(filepath, "wb") as f:
  1071. f.write(envelope.original_content)
  1072. LOG.d("Write email to sender at %s", filepath)
  1073. msg = email.message_from_bytes(envelope.original_content)
  1074. orig = get_orig_message_from_bounce(msg)
  1075. if orig:
  1076. LOG.warning(
  1077. "Original message %s -> %s saved at %s", orig["From"], orig["To"], filepath
  1078. )
  1079. return "250 email to sender accepted"
  1080. async def handle(envelope: Envelope, smtp: SMTP) -> str:
  1081. """Return SMTP status"""
  1082. # unsubscribe request
  1083. if UNSUBSCRIBER and envelope.rcpt_tos == [UNSUBSCRIBER]:
  1084. LOG.d("Handle unsubscribe request from %s", envelope.mail_from)
  1085. return handle_unsubscribe(envelope)
  1086. # emails sent to sender. Probably bounce emails
  1087. if SENDER and envelope.rcpt_tos == [SENDER]:
  1088. LOG.d("Handle email sent to sender from %s", envelope.mail_from)
  1089. return handle_sender_email(envelope)
  1090. # Whether it's necessary to apply greylisting
  1091. if greylisting_needed(envelope.mail_from, envelope.rcpt_tos):
  1092. LOG.warning(
  1093. "Grey listing applied for %s %s", envelope.mail_from, envelope.rcpt_tos
  1094. )
  1095. return "421 SL Retry later"
  1096. # result of all deliveries
  1097. # each element is a couple of whether the delivery is successful and the smtp status
  1098. res: [(bool, str)] = []
  1099. for rcpt_to in envelope.rcpt_tos:
  1100. msg = email.message_from_bytes(envelope.original_content)
  1101. # Reply case
  1102. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  1103. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  1104. LOG.debug(
  1105. ">>> Reply phase %s(%s) -> %s", envelope.mail_from, msg["From"], rcpt_to
  1106. )
  1107. is_delivered, smtp_status = await handle_reply(envelope, smtp, msg, rcpt_to)
  1108. res.append((is_delivered, smtp_status))
  1109. else: # Forward case
  1110. LOG.debug(
  1111. ">>> Forward phase %s(%s) -> %s",
  1112. envelope.mail_from,
  1113. msg["From"],
  1114. rcpt_to,
  1115. )
  1116. for is_delivered, smtp_status in await handle_forward(
  1117. envelope, smtp, msg, rcpt_to
  1118. ):
  1119. res.append((is_delivered, smtp_status))
  1120. for (is_success, smtp_status) in res:
  1121. # Consider all deliveries successful if 1 delivery is successful
  1122. if is_success:
  1123. return smtp_status
  1124. # Failed delivery for all, return the first failure
  1125. return res[0][1]
  1126. async def get_spam_score(message: Message) -> float:
  1127. sa_input = to_bytes(message)
  1128. # Spamassassin requires to have an ending linebreak
  1129. if not sa_input.endswith(b"\n"):
  1130. LOG.d("add linebreak to spamassassin input")
  1131. sa_input += b"\n"
  1132. try:
  1133. # wait for at max 300s which is the default spamd timeout-child
  1134. response = await asyncio.wait_for(
  1135. aiospamc.check(sa_input, host=SPAMASSASSIN_HOST), timeout=300
  1136. )
  1137. return response.headers["Spam"].score
  1138. except asyncio.TimeoutError:
  1139. LOG.exception("SpamAssassin timeout")
  1140. # return a negative score so the message is always considered as ham
  1141. return -999
  1142. except Exception:
  1143. LOG.exception("SpamAssassin exception")
  1144. return -999
  1145. class MailHandler:
  1146. def __init__(self, lock):
  1147. self.lock = lock
  1148. async def handle_DATA(self, server, session, envelope: Envelope):
  1149. try:
  1150. ret = await self._handle(envelope)
  1151. return ret
  1152. except Exception:
  1153. LOG.exception(
  1154. "email handling fail %s -> %s", envelope.mail_from, envelope.rcpt_tos,
  1155. )
  1156. return "421 SL Retry later"
  1157. async def _handle(self, envelope: Envelope):
  1158. async with self.lock:
  1159. start = time.time()
  1160. LOG.info(
  1161. "===>> New message, mail from %s, rctp tos %s ",
  1162. envelope.mail_from,
  1163. envelope.rcpt_tos,
  1164. )
  1165. if POSTFIX_SUBMISSION_TLS:
  1166. smtp = SMTP(POSTFIX_SERVER, 587)
  1167. smtp.starttls()
  1168. else:
  1169. smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25)
  1170. app = new_app()
  1171. with app.app_context():
  1172. ret = await handle(envelope, smtp)
  1173. LOG.info("takes %s seconds <<===", time.time() - start)
  1174. return ret
  1175. if __name__ == "__main__":
  1176. if LOAD_PGP_EMAIL_HANDLER:
  1177. LOG.warning("LOAD PGP keys")
  1178. app = create_app()
  1179. with app.app_context():
  1180. load_pgp_public_keys()
  1181. loop = asyncio.new_event_loop()
  1182. asyncio.set_event_loop(loop)
  1183. lock = asyncio.Lock()
  1184. handler = MailHandler(lock)
  1185. def factory():
  1186. return aiosmtpd.smtp.SMTP(handler, enable_SMTPUTF8=True)
  1187. server = loop.run_until_complete(
  1188. loop.create_server(factory, host="0.0.0.0", port=20381)
  1189. )
  1190. try:
  1191. loop.run_forever()
  1192. except KeyboardInterrupt:
  1193. pass
  1194. # Close the server
  1195. LOG.info("Close SMTP server")
  1196. server.close()
  1197. loop.run_until_complete(server.wait_closed())
  1198. loop.close()