email_handler.py 44 KB

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