From 9377e2a0ed73b80ff875dad04381ca9ac6782b41 Mon Sep 17 00:00:00 2001 From: Son NK Date: Wed, 8 Jan 2020 21:38:41 +0100 Subject: [PATCH] Create alias on the fly if it belongs to a directory --- email_handler.py | 52 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/email_handler.py b/email_handler.py index 20ff8e3c..03cd7b5b 100644 --- a/email_handler.py +++ b/email_handler.py @@ -50,7 +50,7 @@ from app.email_utils import ( ) from app.extensions import db from app.log import LOG -from app.models import GenEmail, ForwardEmail, ForwardEmailLog, CustomDomain +from app.models import GenEmail, ForwardEmail, ForwardEmailLog, CustomDomain, Directory from app.utils import random_string from server import create_app @@ -112,20 +112,46 @@ class MailHandler: if not gen_email: LOG.d("alias %s not exist") - # check if alias is custom-domain alias and if the custom-domain has catch-all enabled - alias_domain = get_email_domain_part(alias) - custom_domain = CustomDomain.get_by(domain=alias_domain) - if custom_domain and custom_domain.catch_all: - LOG.d("create alias %s for domain %s", alias, custom_domain) + # try to see if alias could be created on-the-fly + on_the_fly = False - gen_email = GenEmail.create( - email=alias, - user_id=custom_domain.user_id, - custom_domain_id=custom_domain.id, - automatic_creation=True, - ) - db.session.commit() + # check if alias belongs to a directory. In this case alias has one of the 2 formats: + # directory/anything@EMAIL_DOMAIN or directory+anything@EMAIL_DOMAIN + if alias.endswith(EMAIL_DOMAIN): + if "+" in alias or "/" in alias: + if "+" in alias: + directory_name = alias[alias.find("+")] + else: + directory_name = alias[alias.find("/")] + + directory = Directory.get_by(name=directory_name) + if directory: + LOG.d("create alias %s for directory %s", alias, directory) + on_the_fly = True + + gen_email = GenEmail.create( + email=alias, + user_id=directory.user_id, + directory_id=directory.id, + ) + db.session.commit() else: + # check if alias is custom-domain alias and if the custom-domain has catch-all enabled + alias_domain = get_email_domain_part(alias) + custom_domain = CustomDomain.get_by(domain=alias_domain) + if custom_domain and custom_domain.catch_all: + LOG.d("create alias %s for domain %s", alias, custom_domain) + on_the_fly = True + + gen_email = GenEmail.create( + email=alias, + user_id=custom_domain.user_id, + custom_domain_id=custom_domain.id, + automatic_creation=True, + ) + db.session.commit() + + if not on_the_fly: return "510 Email not exist" user_email = gen_email.user.email