我有这个代码,它似乎能够登录Gmail并查看电子邮件(未读电子邮件被标记为已读)。但是,没有下载,我不知道为什么。关于如何实现这一目标的任何想法?
import email
import getpass, imaplib
import os
import sys
detach_dir = '.'
if 'attachments' not in os.listdir(detach_dir):
os.mkdir('attachments')
userName = input('Enter your GMail username:')
passwd = getpass.getpass('Enter your password: ')
imapSession = imaplib.IMAP4_SSL('imap.gmail.com')
typ, accountDetails = imapSession.login(userName, passwd)
if typ != 'OK':
print ('Not able to sign in!')
raise
imapSession.select('Inbox')
typ, data = imapSession.search(None, 'ALL')
if typ != 'OK':
print ('Error searching Inbox.')
raise
# Iterating over all emails
for msgId in data[0].split(): typ, messageParts = imapSession.fetch(msgId,
'(RFC822)')
if typ != 'OK':
print ('Error fetching mail.')
raise
emailBody = messageParts[0][1]
mail = email.message_from_string(emailBody)
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
# print part.as_string()
continue
if part.get('Content-Disposition') is None:
# print part.as_string()
continue
fileName = part.get_filename()
if bool(fileName):
filePath = os.path.join(detach_dir, 'attachments', fileName)
if not os.path.isfile(filePath) :
print (fileName)
fp = open(filePath, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
imapSession.close()
imapSession.logout()
我正在使用类似的代码,我遇到了同样的问题。为了解决这个问题,我改变了
mail = email.message_from_string(emailBody)
至
mail = email.message_from_bytes(emailBody)
这对我有用。希望能帮助到你!