我跟随a tutorial以便能够阅读电子邮件元数据。我收到以下错误:imaplib.error: UID command error: BAD [b'Could not parse command']
完整的痕迹是:
Traceback (most recent call last):
File "email_metadata.py", line 28, in <module>
result, data = conn.uid('fetch', ','.join(str(u) for u in uids), '(BODY[HEADER.FIELDS (MESSAGE-ID FROM TO CC DATE)])')
File "/usr/lib/python3.4/imaplib.py", line 817, in uid
typ, dat = self._simple_command(name, command, *args)
File "/usr/lib/python3.4/imaplib.py", line 1134, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/lib/python3.4/imaplib.py", line 965, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: UID command error: BAD [b'Could not parse command']
这是我的代码: 完整的代码在我的要点
import imaplib, email, getpass
from email.utils import getaddresses
imaplib._MAXLINE = 40000
#connection
conn = imaplib.IMAP4_SSL('imap.gmail.com')
(retcode, capabilities) = conn.login('my_true_email_addr@gmail.com', getpass.getpass())
print(conn.list())
#print con.list()
conn.select("INBOX", readonly=True)
result, data = conn.uid('search', None, '(SINCE "01-Jan-2014" BEFORE "01-Jan-2015")')
uids = data[0].split()
print(uids)#in bytes
# Download headers
result, data = conn.uid('fetch', ','.join(str(u) for u in uids), '(BODY[HEADER.FIELDS (MESSAGE-ID FROM TO CC DATE)])')
# Where data will be stored
raw_file = open('raw-email-rec.tsv', 'w')
# Header for TSV file
raw_file.write("Message-ID\tDate\tFrom\tTo\tCc\n")
以前这行.join(str(u) for u in uids)
就像这个.join(uids)
一样写在教程中,但我发错了TypeError: sequence item 0: expected str instance, bytes found
所以我把它转换成了字符串。
答案 0 :(得分:3)
我认为你转换了错误的东西。看起来该库正在使用bytes
而不是str
。尝试:
b','.join(uids)
答案 1 :(得分:1)
我将字节列表转换为字符串
result, data = conn.uid('search', None, '(SINCE "01-Jan-2014" BEFORE "05-Jan-2015")')
print(data)
#[b'2627 2628 2630 2639 2643 2649 2650 2651 2652']
uids = data[0].split()
#[b'2627', b'2628', b'2630', b'2639', b'2643', b'2649', b'2650', b'2651', b'2652']
uids = [i.decode('utf-8') for i in uids]
#['2627', '2628', '2630', '2639', '2643', '2649', '2650', '2651', '2652']
# Download headers
result, data = conn.uid('fetch', ','.join(uids), '(BODY[HEADER.FIELDS (MESSAGE-ID FROM TO CC DATE)])')
print(','.join(uids))
#'2627,2628,2630,2639,2643,2649,2650,2651,2652'