From f439e39580543791bcb5f4d171d586def84dc64d Mon Sep 17 00:00:00 2001 From: Son Date: Wed, 29 Dec 2021 16:26:37 +0100 Subject: [PATCH] cache smtp server and remove POSTFIX_PORT_FORWARD --- app/api/views/auth.py | 2 +- app/config.py | 5 ----- app/email_utils.py | 25 ++++++++++++++++--------- 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/app/api/views/auth.py b/app/api/views/auth.py index 1958426b..75f7772c 100644 --- a/app/api/views/auth.py +++ b/app/api/views/auth.py @@ -272,7 +272,7 @@ def auth_facebook(): @api_bp.route("/auth/google", methods=["POST"]) def auth_google(): """ - Authenticate user with Facebook + Authenticate user with Google Input: google_token: Google access token device: to create an ApiKey associated with this device diff --git a/app/config.py b/app/config.py index 3ff40f65..575e5741 100644 --- a/app/config.py +++ b/app/config.py @@ -117,11 +117,6 @@ POSTFIX_PORT = 25 if "POSTFIX_PORT" in os.environ: POSTFIX_PORT = int(os.environ["POSTFIX_PORT"]) -# postfix port to use during the forward phase -POSTFIX_PORT_FORWARD = POSTFIX_PORT -if "POSTFIX_PORT_FORWARD" in os.environ: - POSTFIX_PORT_FORWARD = int(os.environ["POSTFIX_PORT_FORWARD"]) - # Use port 587 instead of 25 when sending emails through Postfix # Useful when calling Postfix from an external network POSTFIX_SUBMISSION_TLS = "POSTFIX_SUBMISSION_TLS" in os.environ diff --git a/app/email_utils.py b/app/email_utils.py index eeae62fd..b4cbea57 100644 --- a/app/email_utils.py +++ b/app/email_utils.py @@ -19,6 +19,7 @@ import arrow import dkim import re2 as re import spf +from cachetools import cached, TTLCache from email_validator import ( validate_email, EmailNotValidError, @@ -49,7 +50,6 @@ from app.config import ( ALERT_DIRECTORY_DISABLED_ALIAS_CREATION, TRANSACTIONAL_BOUNCE_EMAIL, ALERT_SPF, - POSTFIX_PORT_FORWARD, TEMP_DIR, ALIAS_AUTOMATIC_DISABLE, RSPAMD_SIGN_DKIM, @@ -1264,6 +1264,19 @@ def spf_pass( return True +# cache the smtp server for 20 seconds +@cached(cache=TTLCache(maxsize=2, ttl=20)) +def get_smtp_server(): + LOG.d("get a smtp server") + if POSTFIX_SUBMISSION_TLS: + smtp = SMTP(POSTFIX_SERVER, 587) + smtp.starttls() + else: + smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT) + + return smtp + + def sl_sendmail( from_addr, to_addr, @@ -1284,14 +1297,8 @@ def sl_sendmail( return try: - if POSTFIX_SUBMISSION_TLS: - smtp = SMTP(POSTFIX_SERVER, 587) - smtp.starttls() - else: - if is_forward: - smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT_FORWARD) - else: - smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT) + # to avoid creating SMTP server every time + smtp = get_smtp_server() # smtp.send_message has UnicodeEncodeError # encode message raw directly instead