python自动下载邮件附件_python根据邮件的接收时间来下载指定附件

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值