I want to extract the first number found in an e-mail body. With the help with email library I extracted just the body from the mail to a string. But the problem is that before the real plain-text body begins there is some info about encoding and such (those contains digits). How can I skip those on a reliable way that is undependent on which client that created the e-mail and just ge the first number.
If I do a
match = re.search('\d+', string, re.MULTILINE)
It will get the first match in the info about encoding or something and not in the actual mail content.
Ok. I add a sample. This is how it could look (i will extract 123). But I suppose it could look different went sent from another client.
--14dae93404410f62f404b2e65e10 Content-Type: text/plain; charset=ISO-8859-1 Junk 123 Junk --14dae93404410f62f404b2e65e10 Content-Type: text/html; charset=ISO-8859-1 <p>Junk 123 Junk</p> --14dae93404410f62f404b2e65e10--
Update:
Now I’m stuck with the iterator :-/ I really tried. But I don’t get it. This code:
msg = email.message_from_string(raw_message)
for part in email.iterators.typed_subpart_iterator(msg, 'text', 'plain'):
print part
outputs:
--14dae93404410f62f404b2e65e10
Content-Type: text/plain; charset=ISO-8859-1
Junk 123 Junk
--14dae93404410f62f404b2e65e10
Content-Type: text/html; charset=ISO-8859-1
<p>Junk 123 Junk</p>
--14dae93404410f62f404b2e65e10--
Why won’t it just output:
Junk 123 Junk
?
You may want to use the iterators to skip over the subpart headers.
http://docs.python.org/library/email.iterators.html#module-email.iterators
This example will print the body of each message subpart that is text/plain: