address.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. class EmailAddress:
  2. """Format class for email addresses.
  3. This class is useful manipulate the
  4. addresses in templates with minimal
  5. effort. More about email addresses from
  6. `Wikipedia <https://en.wikipedia.org/wiki/Email_address>`_.
  7. Parameters
  8. ----------
  9. address : str
  10. Email address as string.
  11. """
  12. def __init__(self, address:str):
  13. self.address = address
  14. def __str__(self):
  15. return self.address
  16. # From official specs
  17. @property
  18. def parts(self):
  19. return self.address.split("@")
  20. @property
  21. def local_part(self):
  22. return self.parts[0]
  23. @property
  24. def domain(self):
  25. "bool: Domain of the address"
  26. return self.parts[1]
  27. @property
  28. def is_personal(self):
  29. "bool: Whether the email address seems to belong to a person"
  30. return len(self.local_part.split(".")) == 2
  31. # More of typical conventions
  32. @property
  33. def top_level_domain(self):
  34. """Get top level domain (if possible)
  35. Ie. john.smith@en.example.com --> com"""
  36. domain = self.domain.split(".")
  37. return '.' + domain[-1] if len(domain) > 1 else None
  38. @property
  39. def second_level_domain(self):
  40. """Get second level domain (if possible)
  41. Ie. john.smith@en.example.com --> example"""
  42. domain = self.domain.split(".")
  43. return domain[-2] if len(domain) > 1 else None
  44. @property
  45. def full_name(self) -> str:
  46. """str: Full name of the address
  47. """
  48. if self.is_personal:
  49. return f'{self.first_name.capitalize()} {self.last_name.capitalize()}'
  50. else:
  51. return self.local_part.capitalize()
  52. @property
  53. def first_name(self) -> str:
  54. """str: First name of the address (if in typical form)"""
  55. if self.is_personal:
  56. return self.local_part.split(".")[0].capitalize()
  57. @property
  58. def last_name(self) -> str:
  59. """str: Last name of the address (if in typical form)"""
  60. if self.is_personal:
  61. return self.local_part.split(".")[1].capitalize()
  62. # Aliases
  63. @property
  64. def organization(self) -> str:
  65. """str: Organization"""
  66. return self.second_level_domain.capitalize()