# -*- encoding: utf-8 -*-
# -*- encoding: gbk -*-
import getpass, email, sys
from imapclient import IMAPClient
import datetime
import time
import os
################################################
account = "邮箱账户" # 填写你得邮箱账户
pwd = "邮箱密码" # 填写你得邮箱密码
target_email = "指定账号的邮件" # 填写你要获取的指定邮件账号
outlock_host = 'imap-mail.outlook.com' # 填写你的outlock服务器地址
###################################################
# 登入指定邮箱服务器
with IMAPClient(outlock_host, use_uid=True) as server:
# 输入用户名和密码
server.login(account, pwd)
print('success')
# 查询邮箱中文件夹信息
listfolders = server.list_folders()
# 查询指定邮箱的邮件信息
select_info = server.select_folder('INBOX')
print('%d messages in INBOX' % select_info[b'EXISTS'])
# 查询来至指定账号的邮件
messages = server.search(['FROM', target_email])
# 解码邮件信息
for uid, message_data in server.fetch(messages, 'RFC822').items():
email_message = email.message_from_bytes(message_data[b'RFC822'])
subject = email.header.make_header(email.header.decode_header(email_message['SUBJECT']))
mail_from = email.header.make_header(email.header.decode_header(email_message['From']))
date = email.header.decode_header(email_message.get('date'))
print(date)
utcstr = date[0][0].replace('+00:00', '')
print(utcstr)
try:
utcdatetime = datetime.datetime.strptime(utcstr, '%a, %d %b %Y %H:%M:%S +0000 (GMT)')
print(utcdatetime)
localdatetime = utcdatetime + datetime.timedelta(hours=+8)
print(localdatetime)
localtimestamp = localdatetime.timestamp()
print(localtimestamp)
except:
utcdatetime = datetime.datetime.strptime(utcstr, '%a, %d %b %Y %H:%M:%S +0800')
localtimestamp = utcdatetime.timestamp()
print(uid, subject, mail_from)
# print(localtimestamp)
days = time.strftime("%Y%m%d", time.localtime(localtimestamp))
if days >= time.strftime("%Y%m%d", time.localtime(time.time() - 172800)):
# 提取附件信息
attachment_files = []
for part in email_message.walk():
file_name = part.get_filename()
if file_name:
h = email.header.Header(file_name)
# 对附件名称进行解码
dh = email.header.decode_header(h)
filename = dh[0][0]
if dh[0][1]:
# 将附件名称可读化
filename = email.header.make_header(email.header.decode_header(str(filename, dh[0][1])))
print(filename)
# 下载附件
data = part.get_payload(decode=True)
# 在指定目录下创建文件,注意二进制文件需要用wb模式打开
att_file = open(os.getcwd() + '\\' + str(filename), 'wb')
attachment_files.append(filename)
att_file.write(data) # 保存附件
att_file.close()
else:
print('非最近两天的邮件')
outlock2
最新推荐文章于 2022-02-03 15:05:00 发布