address.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. class EmailAddress:
  2. """Utility class to represent email
  3. address and access the organization/
  4. names in it.
  5. https://en.wikipedia.org/wiki/Email_address
  6. """
  7. def __init__(self, address:str):
  8. self.address = address
  9. def organization(self):
  10. return self.address.split("@")
  11. def __str__(self):
  12. return self.address
  13. # From official specs
  14. @property
  15. def parts(self):
  16. return self.address.split("@")
  17. @property
  18. def local_part(self):
  19. return self.parts[0]
  20. @property
  21. def domain(self):
  22. return self.parts[1]
  23. # Checks
  24. @property
  25. def is_personal(self):
  26. "Whether the email address seems to belong to a person"
  27. return len(self.local_part.split(".")) == 2
  28. # More of typical conventions
  29. @property
  30. def top_level_domain(self):
  31. """Get top level domain (if possible)
  32. Ie. john.smith@en.example.com --> com"""
  33. domain = self.domain.split(".")
  34. return domain[-1] if len(domain) > 1 else None
  35. @property
  36. def second_level_domain(self):
  37. """Get second level domain (if possible)
  38. Ie. john.smith@en.example.com --> example"""
  39. domain = self.domain.split(".")
  40. return domain[-2] if len(domain) > 1 else None
  41. @property
  42. def full_name(self):
  43. """Get full name of the sender (if possible)
  44. Ie. john.smith@en.example.com --> 'john smith'"""
  45. if self.is_personal:
  46. return f'{self.first_name} {self.last_name}'
  47. else:
  48. return self.local_part.capitalize()
  49. @property
  50. def first_name(self):
  51. """Get first name of the sender (if possible)
  52. Ie. john.smith@en.example.com --> John"""
  53. if self.is_personal:
  54. return self.local_part.split(".")[0].capitalize()
  55. @property
  56. def last_name(self):
  57. """Get last name of the sender (if possible)
  58. Ie. john.smith@en.example.com --> Smith"""
  59. if self.is_personal:
  60. return self.local_part.split(".")[1].capitalize()
  61. # Aliases
  62. @property
  63. def organization(self):
  64. """This is alias for second level domain."""
  65. return self.second_level_domain