Search code examples
pythonregeximaplib

Splitting Account Name from email address


I've search thru the net but I saw splitting email addresses which doesn't satisfy my needs.
Basically imaplib returns the sender's email as

Account Name <[email protected]>

I need to extract the email address only because that's what the only thing I'm going to use. Kinda new to regex, so insights will be awesome, Thanks in advance!

My code to extract sender details incase it's needed

for i in range (1, messages+1, +1):
    # fetch the email message by ID
    res, msg = mail.fetch(str(i), "(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT)])")
    for response in msg:
        if isinstance(response, tuple):
            # parse a bytes email into a message object
            msg = email.message_from_bytes(response[1])
            # decode email sender
            From, encoding = decode_header(msg.get("From"))[0]
            if isinstance(From, bytes):
                From = From.decode(encoding)
            print("From:", From)

Solution

  • Test this expression if it works:

    (?!<)[\w_@.]+(?=>)

    Here is my test:

    enter image description here

    I am using RegExr to test this regex: https://regexr.com/