私は最終的に最終プロジェクトとしてスパム分類アプリケーションを終了しましたが、今は問題に直面しています。 問題は電子メールを受信するモジュールから発生しました。私は単一の.pyファイルにテストコードを書いて、それは本当にうまくいった。ここでは、コードは次のようになります。文字エンコーディング:私の電子メール受信コードをPyQt4で実行できないのはなぜですか?
#!/usr/bin/env python
# coding=utf-8
import poplib
from email import parser
host = 'pop.qq.com'
username = '[email protected]'
password = 'xxxxxxxxxxxxx'
pop_conn = poplib.POP3_SSL(host)
pop_conn.user(username)
pop_conn.pass_(password)
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#print messages
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
i = 0
for message in messages:
i = i + 1
mailName = "mail"+str(i)
f = open(mailName + '.log', 'w');
print >> f, "Date: ", message["Date"]
print >> f, "From: ", message["From"]
print >> f, "To: ", message["To"]
print >> f, "Subject: ", message["Subject"]
print >> f, "Data: "
for part in message.walk():
contentType = part.get_content_type()
if contentType == 'text/plain' :
data = part.get_payload(decode=True)
print >> f, data
f.close()
pop_conn.quit()
しかし、私は私のPyQt4アプリとまったく同じコードを移植しようとしたとき、問題は、この行に出てきた:
messages = ["\n".join(mssg[1]) for mssg in messages]
、これは問題です:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 4:ordinal not in range(128)
mssg [1]は、メールのすべての行を含むリストです。これは、メールのテキストがデフォルトの "ascii"でデコードできない "utf-8"または "gbk"でエンコードされているためです。だから私はこのようなコードを書くことを試みた:
messages = ["\n".join([m.decode("utf-8") for m in mssg[1]]) for mssg in messages]
問題は、このようになりました:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcc in position 7
私は、電子メールのテキストのエンコーディングを検出するために、Pythonのchardetモジュールを使用し、それが判明しました「アスキー」となる。今私は本当に混乱しています。なぜ私の小さなアプリケーションで同じコードを実行できないのですか?本当の問題とは何ですか?私はそれをどのように修正できますか?私はあなたの助けに非常に感謝します。
画像タグの前に '!'文字を追加して正しく表示してください。 – surajsn
thx〜イメージを投稿するのに十分な評判がないので、代わりにエラーメッセージをタイプします:-D – ZhenLian