Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse small string for name and email?

Tags:

python

email

I have a string:

John Smith <[email protected]>

I would like to get two variables:

name (John Smith) and email ([email protected])

How might I do that?

Thanks for the help!

like image 778
Andrew Avatar asked Jun 02 '11 02:06

Andrew


1 Answers

There are more forms of valid Internet Email address than you probably realize. I would suggest using somebody else's code to parse them, like email.utils.parseaddr.

For example, the following is a valid address:

"Rocky J. Squirrel" <[email protected]>

Here, the name is Rocky J. Squirrel, not "Rocky J. Squirrel".

The following is also legal syntax and shows up regularly in mail headers (note lack of <> delimiters):

[email protected] (Rocky J. Squirrel)

Although the part in parens is technically just a "comment", most mail clients interpret it as the user's name. (And so does Python's email.utils.parseaddr.)

To actually do the parsing (saving you reading the docs):

>>> import email.utils
>>> email.utils.parseaddr("John Smith <[email protected]>")
('John Smith', '[email protected]')
like image 132
Nemo Avatar answered Oct 30 '22 19:10

Nemo