Skip to main content
 首页 » 编程设计

python之解析电子邮件并从正文中获取号码

2025年05月04日32txw1958

我想提取在电子邮件正文中找到的第一个数字。在电子邮件库的帮助下,我只将正文从邮件中提取为一个字符串。但问题是,在真正的纯文本正文开始之前,有一些关于编码等的信息(包含数字)。我怎样才能以一种可靠的方式跳过那些不依赖于创建电子邮件的客户端并且只获取第一个数字的可靠方式。

如果我做一个

match = re.search('\d+', string, re.MULTILINE) 

它将在有关编码或其他内容的信息中获得第一个匹配项,而不是在实际邮件内容中。

好的。我添加了一个示例。这就是它的样子(我将提取 123)。但我想它可能看起来不一样,是从另一个客户发送的。

--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 

输出:

--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-- 

为什么不直接输出:

Junk 123 Junk 

?

请您参考如下方法:

您可能希望使用迭代器跳过子部分标题。

http://docs.python.org/library/email.iterators.html#module-email.iterators

此示例将打印文本/纯文本的每个消息子部分的正文:

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