4

次を使用してGmailからメールを抽出しています。

def getMsgs():
 try:
    conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
  except:
    print 'Failed to connect'
    print 'Is your internet connection working?'
    sys.exit()
  try:
    conn.login(username, password)
  except:
    print 'Failed to login'
    print 'Is the username and password correct?'
    sys.exit()

  conn.select('Inbox')
  # typ, data = conn.search(None, '(UNSEEN SUBJECT "%s")' % subject)
  typ, data = conn.search(None, '(SUBJECT "%s")' % subject)
  for num in data[0].split():
    typ, data = conn.fetch(num, '(RFC822)')
    msg = email.message_from_string(data[0][1])
    yield walkMsg(msg)

def walkMsg(msg):
  for part in msg.walk():
    if part.get_content_type() != "text/plain":
      continue
    return part.get_payload()

ただし、「=」などのエンコーディング関連の文字がさまざまなテキストフィールドの中央にランダムに表示されるため、(正規表現を使用して)日付を抽出できないメールもあります。抽出したい日付範囲で発生する例を次に示します。

名前:KIRSTIメール:kirsti@blah.blah電話番号:+ 999 99995192パーティーの合計:合計4人、子供0人到着/出発:2010年10月9日-2010年10月13日-2010年10月13日

これらのエンコード文字を削除する方法はありますか?

4

3 に答える 3

6

You could/should use the email.parser module to decode mail messages, for example (quick and dirty example!):

from email.parser import FeedParser
f = FeedParser()
f.feed("<insert mail message here, including all headers>")
rootMessage = f.close()

# Now you can access the message and its submessages (if it's multipart)
print rootMessage.is_multipart()

# Or check for errors
print rootMessage.defects

# If it's a multipart message, you can get the first submessage and then its payload
# (i.e. content) like so:
rootMessage.get_payload(0).get_payload(decode=True)

Using the "decode" parameter of Message.get_payload, the module automatically decodes the content, depending on its encoding (e.g. quoted printables as in your question).

于 2010-10-28T07:10:31.140 に答える
2

これは、quoted-printableエンコーディングとして知られています。quopri.decodestringおそらく次のようなものを使用したいと思うでしょう-http://docs.python.org/library/quopri.html

于 2010-10-28T05:45:45.200 に答える