email_handler.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  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. start = time.time()
  375. spam_score = await get_spam_score(msg)
  376. LOG.d(
  377. "%s -> %s - spam score %s in %s seconds",
  378. contact,
  379. alias,
  380. spam_score,
  381. time.time() - start,
  382. )
  383. email_log.spam_score = spam_score
  384. db.session.commit()
  385. if (user.max_spam_score and spam_score > user.max_spam_score) or (
  386. not user.max_spam_score and spam_score > MAX_SPAM_SCORE
  387. ):
  388. is_spam = True
  389. spam_status = "Spam detected by SpamAssassin server"
  390. else:
  391. is_spam, spam_status = get_spam_info(msg, max_score=user.max_spam_score)
  392. if is_spam:
  393. LOG.warning("Email detected as spam. Alias: %s, from: %s", alias, contact)
  394. email_log.is_spam = True
  395. email_log.spam_status = spam_status
  396. db.session.commit()
  397. handle_spam(contact, alias, msg, user, mailbox, email_log)
  398. return False, "550 SL E1 Email detected as spam"
  399. # create PGP email if needed
  400. if mailbox.pgp_finger_print and user.is_premium() and not alias.disable_pgp:
  401. LOG.d("Encrypt message using mailbox %s", mailbox)
  402. try:
  403. msg = prepare_pgp_message(msg, mailbox.pgp_finger_print)
  404. except PGPException:
  405. LOG.exception(
  406. "Cannot encrypt message %s -> %s. %s %s", contact, alias, mailbox, user
  407. )
  408. # so the client can retry later
  409. return False, "421 SL E12 Retry later"
  410. # add custom header
  411. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  412. # remove reply-to & sender header if present
  413. delete_header(msg, "Reply-To")
  414. delete_header(msg, "Sender")
  415. delete_header(msg, _IP_HEADER)
  416. add_or_replace_header(msg, _MAILBOX_ID_HEADER, str(mailbox.id))
  417. add_or_replace_header(msg, _EMAIL_LOG_ID_HEADER, str(email_log.id))
  418. # change the from header so the sender comes from @SL
  419. # so it can pass DMARC check
  420. # replace the email part in from: header
  421. contact_from_header = msg["From"]
  422. new_from_header = contact.new_addr()
  423. add_or_replace_header(msg, "From", new_from_header)
  424. LOG.d("new_from_header:%s, old header %s", new_from_header, contact_from_header)
  425. # replace CC & To emails by reply-email for all emails that are not alias
  426. replace_header_when_forward(msg, alias, "Cc")
  427. replace_header_when_forward(msg, alias, "To")
  428. # append alias into the TO header if it's not present in To or CC
  429. if should_append_alias(msg, alias.email):
  430. LOG.d("append alias %s to TO header %s", alias, msg["To"])
  431. if msg["To"]:
  432. to_header = msg["To"] + "," + alias.email
  433. else:
  434. to_header = alias.email
  435. add_or_replace_header(msg, "To", to_header.strip())
  436. # add List-Unsubscribe header
  437. if UNSUBSCRIBER:
  438. unsubscribe_link = f"mailto:{UNSUBSCRIBER}?subject={alias.id}="
  439. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  440. else:
  441. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  442. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  443. add_or_replace_header(
  444. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  445. )
  446. add_dkim_signature(msg, EMAIL_DOMAIN)
  447. LOG.d(
  448. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  449. contact.website_email,
  450. mailbox.email,
  451. envelope.mail_options,
  452. envelope.rcpt_options,
  453. )
  454. # smtp.send_message has UnicodeEncodeErroremail issue
  455. # encode message raw directly instead
  456. smtp.sendmail(
  457. contact.reply_email,
  458. mailbox.email,
  459. msg.as_bytes(),
  460. envelope.mail_options,
  461. envelope.rcpt_options,
  462. )
  463. db.session.commit()
  464. return True, "250 Message accepted for delivery"
  465. async def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> (bool, str):
  466. """
  467. return whether an email has been delivered and
  468. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  469. """
  470. reply_email = rcpt_to.lower().strip()
  471. # reply_email must end with EMAIL_DOMAIN
  472. if not reply_email.endswith(EMAIL_DOMAIN):
  473. LOG.warning(f"Reply email {reply_email} has wrong domain")
  474. return False, "550 SL E2"
  475. contact = Contact.get_by(reply_email=reply_email)
  476. if not contact:
  477. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  478. return False, "550 SL E4 Email not exist"
  479. alias = contact.alias
  480. address: str = contact.alias.email
  481. alias_domain = address[address.find("@") + 1 :]
  482. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  483. if not email_belongs_to_alias_domains(alias.email):
  484. if not CustomDomain.get_by(domain=alias_domain):
  485. return False, "550 SL E5"
  486. user = alias.user
  487. mail_from = envelope.mail_from.lower().strip()
  488. # bounce email initiated by Postfix
  489. # can happen in case emails cannot be delivered to user-email
  490. # in this case Postfix will try to send a bounce report to original sender, which is
  491. # the "reply email"
  492. if mail_from == "<>":
  493. LOG.warning(
  494. "Bounce when sending to alias %s from %s, user %s", alias, contact, user,
  495. )
  496. handle_bounce(contact, alias, msg, user)
  497. return False, "550 SL E6"
  498. mailbox = Mailbox.get_by(email=mail_from, user_id=user.id)
  499. if not mailbox or mailbox not in alias.mailboxes:
  500. # only mailbox can send email to the reply-email
  501. handle_unknown_mailbox(envelope, msg, reply_email, user, alias)
  502. return False, "550 SL E7"
  503. if ENFORCE_SPF and mailbox.force_spf:
  504. ip = msg[_IP_HEADER]
  505. if not spf_pass(ip, envelope, mailbox, user, alias, contact.website_email, msg):
  506. # cannot use 4** here as sender will retry. 5** because that generates bounce report
  507. return True, "250 SL E11"
  508. email_log = EmailLog.create(
  509. contact_id=contact.id, is_reply=True, user_id=contact.user_id
  510. )
  511. # Spam check
  512. spam_status = ""
  513. is_spam = False
  514. # do not use user.max_spam_score here
  515. if SPAMASSASSIN_HOST:
  516. start = time.time()
  517. spam_score = await get_spam_score(msg)
  518. LOG.d(
  519. "%s -> %s - spam score %s in %s seconds",
  520. alias,
  521. contact,
  522. spam_score,
  523. time.time() - start,
  524. )
  525. email_log.spam_score = spam_score
  526. if spam_score > MAX_REPLY_PHASE_SPAM_SCORE:
  527. is_spam = True
  528. spam_status = "Spam detected by SpamAssassin server"
  529. else:
  530. is_spam, spam_status = get_spam_info(msg, max_score=MAX_REPLY_PHASE_SPAM_SCORE)
  531. if is_spam:
  532. LOG.exception(
  533. "Reply phase - email sent from %s to %s detected as spam", alias, contact
  534. )
  535. email_log.is_spam = True
  536. email_log.spam_status = spam_status
  537. db.session.commit()
  538. handle_spam(contact, alias, msg, user, mailbox, email_log, is_reply=True)
  539. return False, "550 SL E15 Email detected as spam"
  540. delete_header(msg, _IP_HEADER)
  541. delete_header(msg, "DKIM-Signature")
  542. delete_header(msg, "Received")
  543. # make the email comes from alias
  544. from_header = alias.email
  545. # add alias name from alias
  546. if alias.name:
  547. LOG.d("Put alias name in from header")
  548. from_header = formataddr((alias.name, alias.email))
  549. elif alias.custom_domain:
  550. LOG.d("Put domain default alias name in from header")
  551. # add alias name from domain
  552. if alias.custom_domain.name:
  553. from_header = formataddr((alias.custom_domain.name, alias.email))
  554. add_or_replace_header(msg, "From", from_header)
  555. # some email providers like ProtonMail adds automatically the Reply-To field
  556. # make sure to delete it
  557. delete_header(msg, "Reply-To")
  558. # remove sender header if present as this could reveal user real email
  559. delete_header(msg, "Sender")
  560. delete_header(msg, "X-Sender")
  561. replace_header_when_reply(msg, alias, "To")
  562. replace_header_when_reply(msg, alias, "Cc")
  563. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  564. delete_header(msg, "Received-SPF")
  565. LOG.d(
  566. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  567. alias.email,
  568. contact.website_email,
  569. envelope.mail_options,
  570. envelope.rcpt_options,
  571. )
  572. # replace "ra+string@simplelogin.co" by the contact email in the email body
  573. # as this is usually included when replying
  574. if user.replace_reverse_alias:
  575. if msg.is_multipart():
  576. for part in msg.walk():
  577. if part.get_content_maintype() != "text":
  578. continue
  579. part = replace_str_in_msg(part, reply_email, contact.website_email)
  580. else:
  581. msg = replace_str_in_msg(msg, reply_email, contact.website_email)
  582. if alias_domain in ALIAS_DOMAINS:
  583. add_dkim_signature(msg, alias_domain)
  584. # add DKIM-Signature for custom-domain alias
  585. else:
  586. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  587. if custom_domain.dkim_verified:
  588. add_dkim_signature(msg, alias_domain)
  589. # create PGP email if needed
  590. if contact.pgp_finger_print and user.is_premium():
  591. LOG.d("Encrypt message for contact %s", contact)
  592. try:
  593. msg = prepare_pgp_message(msg, contact.pgp_finger_print)
  594. except PGPException:
  595. LOG.exception(
  596. "Cannot encrypt message %s -> %s. %s %s", alias, contact, mailbox, user
  597. )
  598. # to not save the email_log
  599. db.session.rollback()
  600. # return 421 so the client can retry later
  601. return False, "421 SL E13 Retry later"
  602. try:
  603. smtp.sendmail(
  604. alias.email,
  605. contact.website_email,
  606. msg.as_bytes(),
  607. envelope.mail_options,
  608. envelope.rcpt_options,
  609. )
  610. except Exception:
  611. # to not save the email_log
  612. db.session.rollback()
  613. LOG.exception("Cannot send email from %s to %s", alias, contact)
  614. send_email(
  615. mailbox.email,
  616. f"Email cannot be sent to {contact.email} from {alias.email}",
  617. render(
  618. "transactional/reply-error.txt",
  619. user=user,
  620. alias=alias,
  621. contact=contact,
  622. contact_domain=get_email_domain_part(contact.email),
  623. ),
  624. render(
  625. "transactional/reply-error.html",
  626. user=user,
  627. alias=alias,
  628. contact=contact,
  629. contact_domain=get_email_domain_part(contact.email),
  630. ),
  631. )
  632. db.session.commit()
  633. return True, "250 Message accepted for delivery"
  634. def spf_pass(
  635. ip: str,
  636. envelope,
  637. mailbox: Mailbox,
  638. user: User,
  639. alias: Alias,
  640. contact_email: str,
  641. msg: Message,
  642. ) -> bool:
  643. if ip:
  644. LOG.d("Enforce SPF")
  645. try:
  646. r = spf.check2(i=ip, s=envelope.mail_from.lower(), h=None)
  647. except Exception:
  648. LOG.exception("SPF error, mailbox %s, ip %s", mailbox.email, ip)
  649. else:
  650. # TODO: Handle temperr case (e.g. dns timeout)
  651. # only an absolute pass, or no SPF policy at all is 'valid'
  652. if r[0] not in ["pass", "none"]:
  653. LOG.warning(
  654. "SPF fail for mailbox %s, reason %s, failed IP %s",
  655. mailbox.email,
  656. r[0],
  657. ip,
  658. )
  659. send_email_with_rate_control(
  660. user,
  661. ALERT_SPF,
  662. mailbox.email,
  663. f"SimpleLogin Alert: attempt to send emails from your alias {alias.email} from unknown IP Address",
  664. render(
  665. "transactional/spf-fail.txt",
  666. name=user.name,
  667. alias=alias.email,
  668. ip=ip,
  669. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  670. to_email=contact_email,
  671. subject=msg["Subject"],
  672. time=arrow.now(),
  673. ),
  674. render(
  675. "transactional/spf-fail.html",
  676. name=user.name,
  677. alias=alias.email,
  678. ip=ip,
  679. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  680. to_email=contact_email,
  681. subject=msg["Subject"],
  682. time=arrow.now(),
  683. ),
  684. )
  685. return False
  686. else:
  687. LOG.warning(
  688. "Could not find %s header %s -> %s",
  689. _IP_HEADER,
  690. mailbox.email,
  691. contact_email,
  692. )
  693. return True
  694. def handle_unknown_mailbox(envelope, msg, reply_email: str, user: User, alias: Alias):
  695. LOG.warning(
  696. f"Reply email can only be used by mailbox. "
  697. f"Actual mail_from: %s. msg from header: %s, reverse-alias %s, %s %s",
  698. envelope.mail_from,
  699. msg["From"],
  700. reply_email,
  701. alias,
  702. user,
  703. )
  704. send_email_with_rate_control(
  705. user,
  706. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  707. user.email,
  708. f"Reply from your alias {alias.email} only works from your mailbox",
  709. render(
  710. "transactional/reply-must-use-personal-email.txt",
  711. name=user.name,
  712. alias=alias,
  713. sender=envelope.mail_from,
  714. ),
  715. render(
  716. "transactional/reply-must-use-personal-email.html",
  717. name=user.name,
  718. alias=alias,
  719. sender=envelope.mail_from,
  720. ),
  721. )
  722. # Notify sender that they cannot send emails to this address
  723. send_email_with_rate_control(
  724. user,
  725. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  726. envelope.mail_from,
  727. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  728. render(
  729. "transactional/send-from-alias-from-unknown-sender.txt",
  730. sender=envelope.mail_from,
  731. reply_email=reply_email,
  732. ),
  733. render(
  734. "transactional/send-from-alias-from-unknown-sender.html",
  735. sender=envelope.mail_from,
  736. reply_email=reply_email,
  737. ),
  738. )
  739. def handle_bounce(contact: Contact, alias: Alias, msg: Message, user: User):
  740. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  741. # Store the bounced email
  742. # generate a name for the email
  743. random_name = str(uuid.uuid4())
  744. full_report_path = f"refused-emails/full-{random_name}.eml"
  745. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  746. file_path = None
  747. mailbox = None
  748. email_log: EmailLog = None
  749. orig_msg = get_orig_message_from_bounce(msg)
  750. if not orig_msg:
  751. # Some MTA does not return the original message in bounce message
  752. # nothing we can do here
  753. LOG.warning(
  754. "Cannot parse original message from bounce message %s %s %s %s",
  755. alias,
  756. user,
  757. contact,
  758. full_report_path,
  759. )
  760. else:
  761. file_path = f"refused-emails/{random_name}.eml"
  762. s3.upload_email_from_bytesio(
  763. file_path, BytesIO(orig_msg.as_bytes()), random_name
  764. )
  765. try:
  766. mailbox_id = int(orig_msg[_MAILBOX_ID_HEADER])
  767. except TypeError:
  768. LOG.exception(
  769. "cannot parse mailbox from original message header %s",
  770. orig_msg[_MAILBOX_ID_HEADER],
  771. )
  772. else:
  773. mailbox = Mailbox.get(mailbox_id)
  774. if not mailbox or mailbox.user_id != user.id:
  775. LOG.exception(
  776. "Tampered message mailbox_id %s, %s, %s, %s %s",
  777. mailbox_id,
  778. user,
  779. alias,
  780. contact,
  781. full_report_path,
  782. )
  783. # cannot use this tampered mailbox, reset it
  784. mailbox = None
  785. # try to get the original email_log
  786. try:
  787. email_log_id = int(orig_msg[_EMAIL_LOG_ID_HEADER])
  788. except TypeError:
  789. LOG.exception(
  790. "cannot parse email log from original message header %s",
  791. orig_msg[_EMAIL_LOG_ID_HEADER],
  792. )
  793. else:
  794. email_log = EmailLog.get(email_log_id)
  795. refused_email = RefusedEmail.create(
  796. path=file_path, full_report_path=full_report_path, user_id=user.id
  797. )
  798. db.session.flush()
  799. LOG.d("Create refused email %s", refused_email)
  800. if not mailbox:
  801. LOG.debug("Try to get mailbox from bounce report")
  802. try:
  803. mailbox_id = int(get_header_from_bounce(msg, _MAILBOX_ID_HEADER))
  804. except Exception:
  805. LOG.exception("cannot get mailbox-id from bounce report, %s", refused_email)
  806. else:
  807. mailbox = Mailbox.get(mailbox_id)
  808. if not mailbox or mailbox.user_id != user.id:
  809. LOG.exception(
  810. "Tampered message mailbox_id %s, %s, %s, %s %s",
  811. mailbox_id,
  812. user,
  813. alias,
  814. contact,
  815. full_report_path,
  816. )
  817. mailbox = None
  818. if not email_log:
  819. LOG.d("Try to get email log from bounce report")
  820. try:
  821. email_log_id = int(get_header_from_bounce(msg, _EMAIL_LOG_ID_HEADER))
  822. except Exception:
  823. LOG.exception(
  824. "cannot get email log id from bounce report, %s", refused_email
  825. )
  826. else:
  827. email_log = EmailLog.get(email_log_id)
  828. # use the default mailbox as the last option
  829. if not mailbox:
  830. LOG.warning("Use %s default mailbox %s", alias, refused_email)
  831. mailbox = alias.mailbox
  832. # create a new email log as the last option
  833. if not email_log:
  834. LOG.warning("cannot get the original email_log, create a new one")
  835. email_log: EmailLog = EmailLog.create(
  836. contact_id=contact.id, user_id=contact.user_id
  837. )
  838. email_log.bounced = True
  839. email_log.refused_email_id = refused_email.id
  840. email_log.bounced_mailbox_id = mailbox.id
  841. db.session.commit()
  842. refused_email_url = (
  843. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  844. )
  845. nb_bounced = EmailLog.filter_by(contact_id=contact.id, bounced=True).count()
  846. if nb_bounced >= 2 and alias.cannot_be_disabled:
  847. LOG.warning("%s cannot be disabled", alias)
  848. # inform user if this is the first bounced email
  849. if nb_bounced == 1 or (nb_bounced >= 2 and alias.cannot_be_disabled):
  850. LOG.d(
  851. "Inform user %s about bounced email sent by %s to alias %s",
  852. user,
  853. contact.website_email,
  854. alias,
  855. )
  856. send_email_with_rate_control(
  857. user,
  858. ALERT_BOUNCE_EMAIL,
  859. user.email,
  860. f"Email from {contact.website_email} to {alias.email} cannot be delivered to your inbox",
  861. render(
  862. "transactional/bounced-email.txt",
  863. name=user.name,
  864. alias=alias,
  865. website_email=contact.website_email,
  866. disable_alias_link=disable_alias_link,
  867. refused_email_url=refused_email_url,
  868. mailbox_email=mailbox.email,
  869. ),
  870. render(
  871. "transactional/bounced-email.html",
  872. name=user.name,
  873. alias=alias,
  874. website_email=contact.website_email,
  875. disable_alias_link=disable_alias_link,
  876. refused_email_url=refused_email_url,
  877. mailbox_email=mailbox.email,
  878. ),
  879. )
  880. # disable the alias the second time email is bounced
  881. elif nb_bounced >= 2:
  882. LOG.d(
  883. "Bounce happens again with alias %s from %s. Disable alias now ",
  884. alias,
  885. contact.website_email,
  886. )
  887. alias.enabled = False
  888. db.session.commit()
  889. send_email_with_rate_control(
  890. user,
  891. ALERT_BOUNCE_EMAIL,
  892. user.email,
  893. f"Alias {alias.email} has been disabled due to second undelivered email from {contact.website_email}",
  894. render(
  895. "transactional/automatic-disable-alias.txt",
  896. name=user.name,
  897. alias=alias,
  898. website_email=contact.website_email,
  899. refused_email_url=refused_email_url,
  900. mailbox_email=mailbox.email,
  901. ),
  902. render(
  903. "transactional/automatic-disable-alias.html",
  904. name=user.name,
  905. alias=alias,
  906. website_email=contact.website_email,
  907. refused_email_url=refused_email_url,
  908. mailbox_email=mailbox.email,
  909. ),
  910. )
  911. def handle_spam(
  912. contact: Contact,
  913. alias: Alias,
  914. msg: Message,
  915. user: User,
  916. mailbox: Mailbox,
  917. email_log: EmailLog,
  918. is_reply=False, # whether the email is in forward or reply phase
  919. ):
  920. # Store the report & original email
  921. orig_msg = get_orig_message_from_spamassassin_report(msg)
  922. # generate a name for the email
  923. random_name = str(uuid.uuid4())
  924. full_report_path = f"spams/full-{random_name}.eml"
  925. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  926. file_path = None
  927. if orig_msg:
  928. file_path = f"spams/{random_name}.eml"
  929. s3.upload_email_from_bytesio(
  930. file_path, BytesIO(orig_msg.as_bytes()), random_name
  931. )
  932. refused_email = RefusedEmail.create(
  933. path=file_path, full_report_path=full_report_path, user_id=user.id
  934. )
  935. db.session.flush()
  936. email_log.refused_email_id = refused_email.id
  937. db.session.commit()
  938. LOG.d("Create spam email %s", refused_email)
  939. refused_email_url = (
  940. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  941. )
  942. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  943. if is_reply:
  944. LOG.d(
  945. "Inform %s (%s) about spam email sent from alias %s to %s",
  946. mailbox,
  947. user,
  948. alias,
  949. contact,
  950. )
  951. send_email_with_rate_control(
  952. user,
  953. ALERT_SPAM_EMAIL,
  954. mailbox.email,
  955. f"Email from {contact.website_email} to {alias.email} is detected as spam",
  956. render(
  957. "transactional/spam-email-reply-phase.txt",
  958. name=user.name,
  959. alias=alias,
  960. website_email=contact.website_email,
  961. disable_alias_link=disable_alias_link,
  962. refused_email_url=refused_email_url,
  963. ),
  964. render(
  965. "transactional/spam-email-reply-phase.html",
  966. name=user.name,
  967. alias=alias,
  968. website_email=contact.website_email,
  969. disable_alias_link=disable_alias_link,
  970. refused_email_url=refused_email_url,
  971. ),
  972. )
  973. else:
  974. # inform user
  975. LOG.d(
  976. "Inform %s (%s) about spam email sent by %s to alias %s",
  977. mailbox,
  978. user,
  979. contact,
  980. alias,
  981. )
  982. send_email_with_rate_control(
  983. user,
  984. ALERT_SPAM_EMAIL,
  985. mailbox.email,
  986. f"Email from {contact.website_email} to {alias.email} is detected as spam",
  987. render(
  988. "transactional/spam-email.txt",
  989. name=user.name,
  990. alias=alias,
  991. website_email=contact.website_email,
  992. disable_alias_link=disable_alias_link,
  993. refused_email_url=refused_email_url,
  994. ),
  995. render(
  996. "transactional/spam-email.html",
  997. name=user.name,
  998. alias=alias,
  999. website_email=contact.website_email,
  1000. disable_alias_link=disable_alias_link,
  1001. refused_email_url=refused_email_url,
  1002. ),
  1003. )
  1004. def handle_unsubscribe(envelope: Envelope):
  1005. msg = email.message_from_bytes(envelope.original_content)
  1006. # format: alias_id:
  1007. subject = msg["Subject"]
  1008. try:
  1009. # subject has the format {alias.id}=
  1010. if subject.endswith("="):
  1011. alias_id = int(subject[:-1])
  1012. # some email providers might strip off the = suffix
  1013. else:
  1014. alias_id = int(subject)
  1015. alias = Alias.get(alias_id)
  1016. except Exception:
  1017. LOG.warning("Cannot parse alias from subject %s", msg["Subject"])
  1018. return "550 SL E8 Wrongly formatted subject"
  1019. if not alias:
  1020. LOG.warning("No such alias %s", alias_id)
  1021. return "550 SL E9 Email not exist"
  1022. # This sender cannot unsubscribe
  1023. mail_from = envelope.mail_from.lower().strip()
  1024. mailbox = Mailbox.get_by(user_id=alias.user_id, email=mail_from)
  1025. if not mailbox or mailbox not in alias.mailboxes:
  1026. LOG.d("%s cannot disable alias %s", envelope.mail_from, alias)
  1027. return "550 SL E10 unauthorized"
  1028. # Sender is owner of this alias
  1029. alias.enabled = False
  1030. db.session.commit()
  1031. user = alias.user
  1032. enable_alias_url = URL + f"/dashboard/?highlight_alias_id={alias.id}"
  1033. for mailbox in alias.mailboxes:
  1034. send_email(
  1035. mailbox.email,
  1036. f"Alias {alias.email} has been disabled successfully",
  1037. render(
  1038. "transactional/unsubscribe-disable-alias.txt",
  1039. user=user,
  1040. alias=alias.email,
  1041. enable_alias_url=enable_alias_url,
  1042. ),
  1043. render(
  1044. "transactional/unsubscribe-disable-alias.html",
  1045. user=user,
  1046. alias=alias.email,
  1047. enable_alias_url=enable_alias_url,
  1048. ),
  1049. )
  1050. return "250 Unsubscribe request accepted"
  1051. def handle_sender_email(envelope: Envelope):
  1052. filename = (
  1053. arrow.now().format("YYYY-MM-DD_HH-mm-ss") + "_" + random_string(10) + ".eml"
  1054. )
  1055. filepath = os.path.join(SENDER_DIR, filename)
  1056. with open(filepath, "wb") as f:
  1057. f.write(envelope.original_content)
  1058. LOG.d("Write email to sender at %s", filepath)
  1059. msg = email.message_from_bytes(envelope.original_content)
  1060. orig = get_orig_message_from_bounce(msg)
  1061. if orig:
  1062. LOG.warning(
  1063. "Original message %s -> %s saved at %s", orig["From"], orig["To"], filepath
  1064. )
  1065. return "250 email to sender accepted"
  1066. async def handle(envelope: Envelope, smtp: SMTP) -> str:
  1067. """Return SMTP status"""
  1068. # unsubscribe request
  1069. if UNSUBSCRIBER and envelope.rcpt_tos == [UNSUBSCRIBER]:
  1070. LOG.d("Handle unsubscribe request from %s", envelope.mail_from)
  1071. return handle_unsubscribe(envelope)
  1072. # emails sent to sender. Probably bounce emails
  1073. if SENDER and envelope.rcpt_tos == [SENDER]:
  1074. LOG.d("Handle email sent to sender from %s", envelope.mail_from)
  1075. return handle_sender_email(envelope)
  1076. # Whether it's necessary to apply greylisting
  1077. if greylisting_needed(envelope.mail_from, envelope.rcpt_tos):
  1078. LOG.warning(
  1079. "Grey listing applied for %s %s", envelope.mail_from, envelope.rcpt_tos
  1080. )
  1081. return "421 SL Retry later"
  1082. # result of all deliveries
  1083. # each element is a couple of whether the delivery is successful and the smtp status
  1084. res: [(bool, str)] = []
  1085. for rcpt_to in envelope.rcpt_tos:
  1086. msg = email.message_from_bytes(envelope.original_content)
  1087. # Reply case
  1088. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  1089. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  1090. LOG.debug(
  1091. ">>> Reply phase %s(%s) -> %s", envelope.mail_from, msg["From"], rcpt_to
  1092. )
  1093. is_delivered, smtp_status = await handle_reply(envelope, smtp, msg, rcpt_to)
  1094. res.append((is_delivered, smtp_status))
  1095. else: # Forward case
  1096. LOG.debug(
  1097. ">>> Forward phase %s(%s) -> %s",
  1098. envelope.mail_from,
  1099. msg["From"],
  1100. rcpt_to,
  1101. )
  1102. for is_delivered, smtp_status in await handle_forward(
  1103. envelope, smtp, msg, rcpt_to
  1104. ):
  1105. res.append((is_delivered, smtp_status))
  1106. for (is_success, smtp_status) in res:
  1107. # Consider all deliveries successful if 1 delivery is successful
  1108. if is_success:
  1109. return smtp_status
  1110. # Failed delivery for all, return the first failure
  1111. return res[0][1]
  1112. async def get_spam_score(message: Message) -> float:
  1113. sa_input = to_bytes(message)
  1114. # Spamassassin requires to have an ending linebreak
  1115. if not sa_input.endswith(b"\n"):
  1116. LOG.d("add linebreak to spamassassin input")
  1117. sa_input += b"\n"
  1118. try:
  1119. # wait for at max 300s which is the default spamd timeout-child
  1120. response = await asyncio.wait_for(
  1121. aiospamc.check(sa_input, host=SPAMASSASSIN_HOST), timeout=300
  1122. )
  1123. return response.headers["Spam"].score
  1124. except asyncio.TimeoutError:
  1125. LOG.exception("SpamAssassin timeout")
  1126. # return a negative score so the message is always considered as ham
  1127. return -999
  1128. except Exception:
  1129. LOG.exception("SpamAssassin exception")
  1130. return -999
  1131. class MailHandler:
  1132. def __init__(self, lock):
  1133. self.lock = lock
  1134. async def handle_DATA(self, server, session, envelope: Envelope):
  1135. try:
  1136. ret = await self._handle(envelope)
  1137. return ret
  1138. except Exception:
  1139. LOG.exception(
  1140. "email handling fail %s -> %s", envelope.mail_from, envelope.rcpt_tos,
  1141. )
  1142. return "421 SL Retry later"
  1143. async def _handle(self, envelope: Envelope):
  1144. async with self.lock:
  1145. start = time.time()
  1146. LOG.info(
  1147. "===>> New message, mail from %s, rctp tos %s ",
  1148. envelope.mail_from,
  1149. envelope.rcpt_tos,
  1150. )
  1151. if POSTFIX_SUBMISSION_TLS:
  1152. smtp = SMTP(POSTFIX_SERVER, 587)
  1153. smtp.starttls()
  1154. else:
  1155. smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25)
  1156. app = new_app()
  1157. with app.app_context():
  1158. ret = await handle(envelope, smtp)
  1159. LOG.info("takes %s seconds <<===", time.time() - start)
  1160. return ret
  1161. if __name__ == "__main__":
  1162. if LOAD_PGP_EMAIL_HANDLER:
  1163. LOG.warning("LOAD PGP keys")
  1164. app = create_app()
  1165. with app.app_context():
  1166. load_pgp_public_keys()
  1167. loop = asyncio.new_event_loop()
  1168. asyncio.set_event_loop(loop)
  1169. lock = asyncio.Lock()
  1170. handler = MailHandler(lock)
  1171. def factory():
  1172. return aiosmtpd.smtp.SMTP(handler, enable_SMTPUTF8=True)
  1173. server = loop.run_until_complete(
  1174. loop.create_server(factory, host="0.0.0.0", port=20381)
  1175. )
  1176. try:
  1177. loop.run_forever()
  1178. except KeyboardInterrupt:
  1179. pass
  1180. # Close the server
  1181. LOG.info("Close SMTP server")
  1182. server.close()
  1183. loop.run_until_complete(server.wait_closed())
  1184. loop.close()