Parse email and get number from body

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

?

Answers


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:

for part in email.iterators.typed_subpart_iterator(msg, 'text', 'plain'):
   for body_line in email.iterators.body_line_iterator(part):
       print body_line

Need Your Help

Phonegap plugin DatePicker not working in landscape mode

objective-c ios cordova phonegap-plugins

I am using the PhoneGap plugin DatePicker (https://github.com/phonegap/phonegap-plugins/tree/master/iOS/DatePicker). It works just fine in portrait mode, but I want to be able to use it in landscap...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.