【发布时间】:2019-04-25 22:13:50
【问题描述】:
如果有人能帮助我解决这个问题,我将不胜感激。
我已经实现了以下代码来阅读“来自 gmail 收件箱的未读电子邮件”。我需要打印“收件人”、“发件人”、“主题”、“正文”和“将附件保存在指定位置”
我这里有 2 个问题。
- 如果有任何带有附件的电子邮件,它会给出错误
Body: [<email.message.Message object at 0x026D1050>, <email.message.Message object at 0x02776B70>]。它会打印所有需要的东西并保存附件,但不会打印正文。
如果不包含附件,这很好用。
- 如果电子邮件正文中包含任何样式,例如“粗体/斜体/下划线/颜色...等”,则不会按原样打印。
示例:Python 打印为 Python=C2=A0i=,有时不同的样式用“*”分隔。
def get_body(email_message):
for payload in email_message.get_payload():
# print('Body:\t', payload.get_payload())
break
return(payload.get_payload())
def read_email(server,uname,pwd):
username = uname
password = pwd
mail = imaplib.IMAP4_SSL(server)
mail.login(username, password)
mail.select("inbox")
try:
result, data = mail.uid('search', None, '(UNSEEN)')
inbox_item_list = data[0].split()
most_recent = inbox_item_list[-1]
result2, email_data = mail.uid('fetch', most_recent, '(RFC822)')
raw_email = email_data[0][1].decode("UTF-8")
email_message = email.message_from_string(raw_email)
for part in email_message.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
att_path = os.path.join(location, filename)
if not os.path.isfile(att_path):
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
print('Downloaded file:', filename)
if email_message.is_multipart():
for payload in email_message.get_payload():
print('To:\t\t', email_message['To'])
print('From:\t', email_message['From'])
print('Subject:', email_message['Subject'])
print('Date:\t',email_message['Date'])
print('Body:\t', get_body(email_message))
break
else:
print('Nothing'])
except IndexError:
print("No new email")
while True:
read_email("imap.gmail.com", "s@gmail.com", "spassword")
time.sleep(10)
非常感谢
【问题讨论】:
-
这是不好的做法,根据需要用
try ... except块括起来more。试试这个答案中的模式python-imaplib-html-body-parsing -
感谢您的回复。我现在已经很简单了。但现在只有 1 个问题。如果它不是文本/纯文本,它不会按原样打印正文。我使用 type() 来查看 body 是什么类型。这就像plain/text/list/str..不同的类型..我们如何处理这个
-
" 正文,如果它不是 text/plain":Edit 您的问题并显示前 100 个字符。跨度>
-
我现在以某种方式设法得到了正文,但我只能得到文本。所有图像都仅以不可读的 URL/样式格式显示。如何解决?