第一次实习,什么也不会,公司让写一个自动定时读取邮件的代码,只好自己去网上搜,踩了很多坑,现在终于弄好了,在这里记录一下,也希望能给需要的人一点帮助。

首先就是登陆邮箱并读取邮件,outlook的话一般使用imap连接,如果是qq邮箱可以使用pop3连接,因为pop3连接一般要求账号是数字开头,但是一般邮件如outlook都是字母开头,所以除了qq邮箱其他建议使用imap。我这边的要求是读取未读邮件。所以email_type选择的是UNSEEN,如果是全部读取可以设置为ALL。

# 登陆邮箱并读取原始邮件
def get_mail(email_address, passsword):# 选择服务器server = imaplib.IMAP4_SSL('outlook.office365.com')server.login(email_address, passsword)inbox = server.select("INBOX")# 搜索匹配的邮件email_type, data = server.search(None, "UNSEEN")# 邮件列表,使用空格分割得到邮件索引msglist = data[0].split()if len(msglist) != 0:# 最新邮件latest = msglist[len(msglist)-1]email_type, datas = server.fetch(latest, '(RFC822)')# 使用utf-8解码text = datas[0][1].decode('utf-8')# 转为email.message对象message = email.message_from_string(text)# 获取未读邮件数量server.select()email_unseen_count = len(server.search(None, 'UNSEEN')[1][0].split())print('未读邮件一共有:', email_unseen_count)email_unseen_id_byte = server.search(None, 'UNSEEN')[1][0].split()email_unseen_id = []for row in email_unseen_id_byte:email_unseen_id.append(row.decode('utf-8'))print(email_unseen_id)return messageelse:print("暂无未读邮件")

然后就是解析邮件内容了,将原始邮件转化为可读邮件,邮件的subject或者email中包含的名字都是经过编码后的字符串,要正常显示就必须decode,定义一个decode函数。

# 将原始邮件转化为可读邮件
def decode_str(s):value, charset = decode_header(s)[0]if charset:value = value.decode(charset)return value

这里有一个注意的点是导入decode_headers时是从email.header中导入,如果从nntplib中导入会因为格式不对而报错。

import email
import imaplib
from email.utils import parseaddr
from email.header import decode_header #正确
#from nntplib import decode_header     错误  

为了防止非utf-8编码的邮件无法显示,定义一个检测邮件编码函数

def guess_charset(msg):charset = msg.get_charset()if charset is None:content_type = msg.get('Content-Type','').lower()pos = content_type.find('charset=')if pos >= 0:charset = content_type[pos + 8:].strip()return charset

接下来是通过循环遍历来读取邮件内容

def print_info(msg, indent=0):if indent == 0:for header in ['From', 'To', 'Subject']:value = msg.get(header, '')if value:if header == 'Subject':value = decode_str(value)else:hdr, addr = parseaddr(value)name = decode_str(hdr)value = u'%s <%s>' % (name, addr)print('%s%s: %s' % ('  ' * indent, header, value))
'''if msg.is_multipart():parts = msg.get_payload()for n, part in enumerate(parts):#print('%spart %s' % ('  ' * indent, n))#print('%s--------------------' % ('  ' * indent))print_info(part, indent + 1)else:content_type = msg.get_content_type()if content_type == 'text/plain' or content_type == 'text/html':content = msg.get_payload(decode=True)charset = guess_charset(msg)if charset:content = content.decode(charset)print('%sText: %s' % ('  ' * indent, content + '...'))else:print('%sAttachment: %s' % ('  ' * indent, content_type))
'''

上面的代码中被注释掉的是邮件的内容,因为我觉得内容太多不想显示所以就注释掉了,有需要的可以自己去掉注释符号。

最后就是主函数调用上面的函数,输出邮件内容了

if __name__ == "__main__":email_addr = "xxxxxxxx@outlook.com"password = "xxxxxxxxx"messageObject = get_mail(email_addr, password)if messageObject:msgDate = messageObject["date"]print("发送时间:%s" % msgDate)res = print_info(messageObject)print(res)

email_addr就是邮件的账号,password就是密码,我还设置了一个发送的时间,是对方发送邮件的时间,如果对方是别的国家,时间可能和这边对不上,我也暂时没找到合适的解决办法

给大家看一下结果,这是不显示邮件内容的情况下

因为想要更加解放人力,所以设置了定时启动程序,这样每天只要打开定时程序就可以了

#定义tick,执行我们的python读取邮件任务
def tick():print("tick! the time is :%s" % datetime.now())os.system("python email_imaplib_t.py")#设置每10分钟运行一次tick,每5分钟睡眠一次
if __name__ == "__main__":scheduler = BackgroundScheduler(timezone="Asia/ShangHai")scheduler.add_job(tick, 'interval', minutes=10, start_date="2022-4-1 15:00:00")scheduler.start()print("Press ctrl + {0} to exit".format('Break' if os.name == 'nt' else 'C'))try:while True:time.sleep(300)print(f"sleep!-{datetime.now()}")except(KeyboardInterrupt, SystemExit):scheduler.shutdown()print("exit the job")

结果如下

python自动定时读取outlook邮件内容相关推荐

  1. Python每天定时发送监控邮件

    不管是在信贷领域还是支付领域,作为一个风控人员,我们都需要对部署的策略模型进行监控,信贷领域可能还需要对客户的逾期表现进行监控.这时,如果我们能用python自动连接数据库,对策略.模型.贷后表现等数 ...

  2. python 自动发微博_用 Python 自动定时发微博

    原标题:用 Python 自动定时发微博 其实小帅b已经挺久没有玩微博了,记得上次玩微博还是为了给周杰伦打榜,不过最近心血来潮,觉得俺的微博账号躺着也是躺着,要不就用 Python 做一个自动定时发微 ...

  3. java mail outlook_无法使用JavaMail读取Outlook邮件,而使用Gmail工作

    基本上,我编写了一个可从收件箱中读取电子邮件的应用程序.我一直使用Gmail发送的电子邮件测试应用程序.但是现在,当我试图阅读从Outlook发送的电子邮件时,我没有收到任何内容.无法使用JavaMa ...

  4. python 读取文件读出来是什么格式-深入学习python解析并读取PDF文件内容的方法...

    这篇文章主要学习了python解析并读取PDF文件内容的方法,包括对学习库的应用,python2.7和python3.6中python解析PDF文件内容库的更新,包括对pdfminer库的详细解释和应 ...

  5. python中读取文件内容-深入学习python解析并读取PDF文件内容的方法

    这篇文章主要学习了python解析并读取PDF文件内容的方法,包括对学习库的应用,python2.7和python3.6中python解析PDF文件内容库的更新,包括对pdfminer库的详细解释和应 ...

  6. python读取pdf文件_深入学习python解析并读取PDF文件内容的方法

    这篇文章主要学习了python解析并读取PDF文件内容的方法,包括对学习库的应用,python2.7和python3.6中python解析PDF文件内容库的更新,包括对pdfminer库的详细解释和应 ...

  7. outlook邮件内容丢失与Mail API异常

    问题现象: 1.当日历发件人名称中存在如:` % ^ { } | \ " < > 特殊字符时,mail api异常 2.当outlook邮件内容中包含如:<  特殊字符时, ...

  8. python写入、读取txt文本内容

    python写入.读取txt文本内容 一. 写入txt文本文件 # 保存数据 def writeData(datalist,savepath):for data in datalist:with op ...

  9. Python Pandas 通过读取txt文件内容创建DataFrame

    本文主要介绍Python中,通过读取txt文件内容创建Pandas的DataFrame,创建DataFrame分别使用pd.DataFrame.from_records()和pd.read_csv() ...

最新文章

  1. 日、德、美、中各国“工业4.0“们的核心差异
  2. 【Java基础】序列化之serialVersionUID
  3. LeetCode Water and Jug Problem(巧妙转换为gcd问题)
  4. 自定义 Spring Boot Starter
  5. 关于毕业租房的一些碎碎念。
  6. Python中的相对文件路径的调用
  7. 将流数据输出到Mysql中
  8. Zookeeper开源客户端curator
  9. 用c语言写图书管理系统设计,C语言图书管理系统设计及实现.doc
  10. uni-app广告总结
  11. PHP微信公众号开发之自动回复
  12. android 正三角,倒三角的实现代码
  13. matlab中最好用的滤波函数,谁有matlab滤波器设计实例,想找个参考,最好是hamming窗,低通 fir滤波器。...
  14. 使用windows自带虚拟机---Hyper-V 管理器
  15. python代码风格指南_记录Python代码:完整指南
  16. 现场工程师出手-PCAPHub与云SSH隧道稳妥实现异地LAN IIoT联测
  17. 全球分布式数据库:Google Spanner翻译
  18. 【逻辑漏洞技巧拓展】————3、逻辑漏洞之密码重置
  19. web开发优秀资源下载
  20. wordpress主题SEO_TDK_链接设置教程

热门文章

  1. alternate端口什么意思_alternate是什么意思
  2. Prior Posterior和Likelihood的理解与几种表达方式
  3. 基于卷积神经网络的口罩佩戴识别与检测
  4. NBIOT----BC28模块使用
  5. 这些年我们用过的CMS建站系统
  6. AutoCAD快速入门(十四):夹点编辑
  7. 游戏服务器之存档读档
  8. estimate, underestimate and overestimate
  9. ZigBee 3.0 Z-Stack 3.01 终端设备入网过程全解析
  10. 15:Named Entity Recognition without Labelled Data: A Weak Supervision Approach