【问题标题】:Python: msg.get_payload() discards needed data, solution wantedPython:msg.get_payload() 丢弃需要的数据,需要解决方案
【发布时间】:2012-07-14 08:54:14
【问题描述】:

您好,我在这里浏览了各种帖子,但没有一个回答我的问题,我有两个问题, 1. 我已经编写了一个脚本来使用 poplib 获取电子邮件,一切正常,直到我尝试解析电子邮件的正文时,它摆脱了标签以及其中的数据,我现在放弃了,在这里寻求帮助希望你伙计们会引导我走向正确的方向,因为我在哪里做错了,或者我应该怎么做才能让它发挥作用。

这是解析器脚本的来源

import sys
import socket
import poplib
import email
import csv
import re
try:
  host = "mail.someserver.com"
  mail = poplib.POP3(host)
  print mail.getwelcome()
  print mail.user("username@someserver.com")
  print mail.pass_("qaiaJWkvZT")
  print mail.stat()
  print mail.list()
  print ""

  emailWriter = csv.writer(open('emailMessages.csv', 'wb'), delimiter=',', quotechar='\'', quoting=csv.QUOTE_MINIMAL)
  emailWriter.writerow(['Messages'])
  if mail.stat()[1] > 0:
      print "You have new mail."
  else:
      print "No new mail."

  print ""

  numMessages = len(mail.list()[1])
  for i in range(numMessages):
      for j in mail.retr(i+1)[1]:
          #print j
          msg = email.message_from_string(j) # new statement
          print msg.get_payload(decode=True)
          #emailWriter.writerow([msg.get_payload(decode=True)]) # new statement

  mail.quit()
  input("Press any key to continue.")
except socket.error as e:
  print "Something went wrong! :(\nREASON:\n{0}:{1}".format(e.errno, e.strerror)
  raise
except:
  print "Something went wrong!", sys.exc_info()[0]
  raise

这是上面脚本生成的输出

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or
g/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
BODY {







}
TD {



}
TH {


}
H1 {

}
TABLE,IMG,A {

}
</style>
</head>
<body>


<p><strong>PO Number:</strong> 35164</p>

<p><strong>Ship To:</strong><br />
Joe Pasloski<br />
16 Redwood Drive<br />Yorkton, SK  S3N2X7<br />
204-473-2218</p>


<table cellspacing="0" cellpadding="5" border="1" width="710" align="left">
<tr>



</tr>
<tr>



</tr>
</table>
</body>
</html>

但是,如果我将脚本更改为直接在循环内打印 j 变量,它会给我这个

Return-Path: <orders@someserver.com>
Delivered-To: username@someserver.com
Received: (qmail 7636 invoked by uid 48); 14 Jul 2012 23:29:11 -0000
Date: 14 Jul 2012 23:29:11 -0000
Message-ID: <20120714232911.7635.qmail@b.inetuhosted.net>
To: username@someserver.com
Subject: Drop Ship Order - Joe Pasloski
From: Someserver.com <orders@someserver.com>
X-Mailer: PHP/5.2.17
MIME-Version: 1.0
Content-Type: multipart/alternative;
         boundary="2631183869_50020"
Reply-to: SomeServer.com <orders@someserver.com>
X-Antivirus: avast! (VPS 120714-2, 07/15/2012), Inbound message
X-Antivirus-Status: Clean

--2631183869_50020
Content-Type: text/plain;
        charset="iso-8859-1"
Content-Transfer-Encoding: 8bit



--2631183869_50020
Content-Type: text/html;
        charset="iso-8859-1"
Content-Transfer-Encoding: 8bit

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or
g/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
BODY {
        MARGIN-TOP: 10px;
        MARGIN-BOTTOM: 10px;
        MARGIN-LEFT: 10px;
        MARGIN-RIGHT: 10px;
        FONT-SIZE: 12px;
        FONT-FAMILY: arial,helvetica,sans-serif
        PADDING: 0px;
}
TD {
        FONT-SIZE: 12px;
        FONT-FAMILY: arial,helvetica,sans-serif
        COLOR: #000000;
}
TH {
        FONT-SIZE: 13px;
        FONT-FAMILY: arial,helvetica,sans-serif
}
H1 {
    FONT-SIZE: 20px
}
TABLE,IMG,A {
        BORDER: 0px;
}
</style>
</head>
<body>


<p><strong>PO Number:</strong> 35164</p>

<p><strong>Ship To:</strong><br />
Joe Pasloski<br />
16 Redwood Drive<br />Yorkton, SK  S3N2X7<br />
204-473-2218</p>

<p><strong>Items:</strong>
<table cellspacing="0" cellpadding="5" border="1" width="710" align="left">
<tr>
        <th align="left" width="100">SKU</th>
        <th align="left" width="550">Product</th>
        <th align="left" width="60">Qty</th>
</tr>
<tr>
        <td>JJ-Hamper-Firetruck</td>
        <td>Frankie's Fire Truck Laundry Hamper</td>
        <td>1</td>
</tr>
</table>
</body>
</html>

如果我需要处理原始消息,我怎样才能有效地让消息的正文部分去除不必要的 html 标签而不丢失任何数据?或者如果可以通过使用 get_payload() 方法,我该怎么做才能让它工作。

请帮忙!

2。 此外,有没有一种方法可以使用正则表达式获取表中包含的所有 SKU 信息?如果你也能提供给我,那将是一个加号。非常感谢

【问题讨论】:

    标签: python regex parsing email pop3


    【解决方案1】:

    好的,我自己找到了答案,文档说明了一切,Python: How to get HTML body of an email message using poplib? 的帖子帮助我朝着正确的方向前进。据我所知,我正在处理的消息不是多部分类型的,并且在应用 get_payload( (这是我所做的

    import html2text # added to my source
    numMessages = len(mail.list()[1])
      for i in range(numMessages):
          for j in mail.retr(i+1)[1]:
    
              msg = email.message_from_string(html2text.html2text(j)) 
              print msg.get_payload(decode=False)
    

    这反过来又给了我

    charset="iso-8859-1"
    
    
    
    
    
    
    
    
    
    
    
    BODY {
    
    
    
    
    
    
    
    
    
    }
    
    
    TD {
    
    
    
    
    
    }
    
    
    TH {
    
    
    
    
    }
    
    
    H1 {
    
    
    
    }
    
    
    TABLE,IMG,A {
    
    
    
    }
    
    
    
    
    
    
    
    
    
    
    **PO Number:** 35170
    
    
    
    
    **Ship To:**
    
    
    Tami Curtis
    
    
    67 E. Spring Creek Pkwy
    
    Providence, UT 84332
    
    
    4357553197
    
    
    
    
    
    
    
    
    
    SKU
    
    
    Product
    
    
    Qty
    
    
    
    
    
    
    JJ-Panel-Isabella-BK-PRT
    
    
    Isabella Black Damask Curtains (2 Panels)
    
    
    1
    

    现在我只需要使用正则表达式对其进行更多清理,以获取不必要的换行符/空格和 css 标记的 reif。

    希望它对其他人也有帮助:) 干杯!

    【讨论】:

      猜你喜欢
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 2017-10-02
      • 2015-06-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      相关资源
      最近更新 更多