title: Decomposing email addresses with Python
body: <p>I'm trying to find the clearest way to parse an email header.</p>
  
  <p>Python's class <a href="https://docs.python.org/3/library/email.message.html" rel="nofollow noreferrer">https://docs.python.org/3/library/email.message.html</a> allows access to the headers such as email['To'].</p>
  
  <p>This is of type _UniqueAddressHeader, which is declared in <a href="https://docs.python.org/3/library/email.headerregistry.html" rel="nofollow noreferrer">https://docs.python.org/3/library/email.headerregistry.html</a>.</p>
  
  <p>email['To'] seems to have no exposed methods and always returns as a composite string.</p>
  
  <p>I've tried explicitly creating an Address type with</p>
  
  <pre><code>mailTo = email.headerregistry.Address(mail['To'])
  </code></pre>
  
  <p>however this doesn't correctly compose the object either - all chars are slurped into the 'display_name' attribute, which is not what we need.</p>
  
  <p>Edit: here's my own function, could probably be made more robust to handle errors such as mismatched <code>&lt;</code> <code>&gt;</code> etc</p>
  
  <pre><code>def addressSplit(e):
      """
      :param e: email.header
      :return: displayName, localpart, domainpart str
      """
      s = str(e)
      displayName = ''
      openB = s.find('&lt;')
      closeB = s.find('&gt;')
      if openB&gt;=0 and closeB&gt;=0:
          displayName = s[:openB].strip(' ')
          s = s[openB+1:closeB].strip(' ')        # this is the address part
      localpart, domainpart = s.split('@')
      return displayName, localpart, domainpart
  </code></pre>