Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sender email address with Python IMAP

Tags:

python

email

imap

I have this python IMAP script, but my problem is that, every time I want to get the sender's email address, (From), I always get the sender's first name followed by their email address:

Example:

Souleiman Benhida <[email protected]>

How can i just extract the email address ([email protected])

I did this before, in PHP:

    $headerinfo = imap_headerinfo($connection, $count)
    or die("Couldn't get header for message " . $count . " : " . imap_last_error());
$from = $headerinfo->fromaddress;

But, in python I can only get the full name w/address, how can I get the address alone? I currently use this:

    typ, data = M.fetch(num, '(RFC822)')
mail = email.message_from_string(data[0][1])
headers = HeaderParser().parsestr(data[0][1]) 
message = parse_message(mail)  #body
org = headers['From']

Thanks!

like image 504
Souleiman Avatar asked Dec 02 '22 03:12

Souleiman


1 Answers

Just one more step, using email.utils:

email.utils.parseaddr(address)

Parse address – which should be the value of some address-containing field such as To or Cc – into its constituent realname and email address parts. Returns a tuple of that information, unless the parse fails, in which case a 2-tuple of ('', '') is returned.

Note: originally referenced rfc822, which is now deprecated.

like image 67
dkarp Avatar answered Dec 05 '22 01:12

dkarp