Browse Source

handle the case email from header has the format "First Last <ab@cd.com>"

Son NK 5 years ago
parent
commit
8d60ebd456
2 changed files with 20 additions and 2 deletions
  1. 12 1
      email_handler.py
  2. 8 1
      tests/test_email_handler.py

+ 12 - 1
email_handler.py

@@ -88,7 +88,7 @@ class MailHandler:
 
         user_email = gen_email.user.email
 
-        website_email = msg["From"]
+        website_email = get_email_part(msg["From"])
 
         forward_email = ForwardEmail.get_by(
             gen_email_id=gen_email.id, website_email=website_email
@@ -253,6 +253,17 @@ def get_email_name(email_from):
     return ""
 
 
+def get_email_part(email_from):
+    """parse email from header and return the email part
+    First Last <ab@cd.com> -> ab@cd.com
+    ab@cd.com -> ""
+    """
+    if "<" in email_from:
+        return email_from[email_from.find("<") + 1 : email_from.find(">")].strip()
+
+    return email_from
+
+
 if __name__ == "__main__":
     controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
 

+ 8 - 1
tests/test_email_handler.py

@@ -1,4 +1,4 @@
-from email_handler import get_email_name
+from email_handler import get_email_name, get_email_part
 
 
 def test_get_email_name():
@@ -6,3 +6,10 @@ def test_get_email_name():
     assert get_email_name("First Last<ab@cd.com>") == "First Last"
     assert get_email_name("  First Last   <ab@cd.com>") == "First Last"
     assert get_email_name("ab@cd.com") == ""
+
+
+def test_get_email_part():
+    assert get_email_part("First Last <ab@cd.com>") == "ab@cd.com"
+    assert get_email_part("First Last<ab@cd.com>") == "ab@cd.com"
+    assert get_email_part("  First Last   <ab@cd.com>") == "ab@cd.com"
+    assert get_email_part("ab@cd.com") == "ab@cd.com"