Souleiman
Souleiman

Reputation: 3438

Get sender email address with Python 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!

Upvotes: 4

Views: 17449

Answers (4)

miksus
miksus

Reputation: 3447

I didn't like the existing solutions so I decided to make a sister library for my email sender called Red Box.

Here is how to search and process emails including getting the from address:

from redbox import EmailBox

# Create email box instance
box = EmailBox(
    host="imap.example.com", 
    port=993,
    username="[email protected]",
    password="<PASSWORD>"
)

# Select an email folder
inbox = box["INBOX"]

# Search and process messages
for msg in inbox.search(unseen=True):

    # Process the message
    print(msg.from_)
    print(msg.to)
    print(msg.subject)
    print(msg.text_body)
    print(msg.html_body)

    # Flag the email as read/seen
    msg.read()

I also wrote extensive documentation for it. It also has query language that fully supports nested logical operations.

Upvotes: 0

Vladimir
Vladimir

Reputation: 6756

My external lib https://github.com/ikvk/imap_tools let you work with mail instead read IMAP specifications.

from imap_tools import MailBox, A

# get all emails from INBOX folder
with MailBox('imap.mail.com').login('[email protected]', 'pwd', 'INBOX') as mailbox:
    for msg in mailbox.fetch(A(all=True)):
        print(msg.date, msg.from_, msg.to, len(msg.text or msg.html))

msg.from_, msg.to - parsed addresses, like: '[email protected]'

Upvotes: 0

Imran Ali
Imran Ali

Reputation: 51

to = email.utils.parseaddr(msg['cc'])

This works for me.

Upvotes: -1

dkarp
dkarp

Reputation: 14763

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.

Upvotes: 21

Related Questions