本帖最后由 XiaoPaiShen 于 2019-11-28 03:28 编辑
我用 imaplib 实现了下载最新标题的功能,只是我无法在QQ邮箱测试,你试试运行对不对
import imaplib
import email
from email.header import decode_header
class Email_Checker:
def __init__(self, email='', password='', server='imap.gmail.com'):
self.server = server
self.email = email
self.password = password
self.mail = imaplib.IMAP4_SSL(self.server)
self.mail.login(self.email, self.password)
self.mail.select('inbox')
self.mail_content = {'plain': None, 'html': None}
self.mail_messages = list()
def decode_content(self, content):
if not content:
return None
value, charset = decode_header(content)[0]
if charset:
value = value.decode(charset)
return value
def filter_mails(self, title):
status, data = self.mail.uid('search', None, "ALL")
email_uids = data[0].split()
for uid in email_uids:
status, content = self.mail.uid('fetch', uid, '(RFC822)')
raw_email = content[0][1]
message = email.message_from_bytes(raw_email)
mail_subject = message['subject']
if mail_subject == title:
self.mail_messages.append(message)
def get_content(self, message):
for part in message.walk():
if part.is_multipart:
content_type = part.get_content_type()
charset = part.get_content_charset()
print("Content_Type: {0} Charset: {1}".format(content_type, charset))
if content_type == 'text/plain':
self.mail_content['plain'] = part.get_payload(decode=True).decode(charset)
elif content_type == 'text/html':
self.mail_content['html'] = part.get_payload(decode=True).decode(charset)
else:
self.mail_content['plain'] = message.get_payload(decode=True).decode(charset)
return self.mail_content['plain'].strip() if self.mail_content['plain'] else self.mail_content['html'].strip()
def download_attachment(self, message):
for part in message.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
filename = self.decode_content(filename)
# print('FileName: ', filename)
if not filename:
continue
# save attachment
with open(filename, 'wb') as attach:
data = part.get_payload(decode=True)
attach.write(data)
print("attachment {0} saved".format(filename))
if __name__ == '__main__':
host = 'pop.qq.com'
username = 'email '
password = 'password'
title = 'first demo'
checker = Email_Checker(username, password, host)
checker.filter_mails(title)
lastest_msg = checker.mail_messages[-1]
checker.download_attachment(lastest_msg)
|