前情
因开发流程需要使用outlook收取邮件,发现通过控件有一定的劣势,研究了RPA的邮件发送源码后,自己写一个循环接收未读邮件的代码,并将每一封邮件中的附件分文件夹存放。 可根据自己需要自行修改逻辑得到不同的返回结果
from ubpa import ioutlook from ubpa import iresult from ubpa.ilog import ILog import tempfile import os __logger = ILog(__file__) __attachment_path = tempfile.gettempdir() + os.sep # 默认保存路径 def recv_outlook(mail_account, subject_filter, mail_inbox, attachment_path, top, mark_as_read=True, only_unread=True): ''' :param mail_account: 邮箱 :param subject_filter: 主题 :param mail_inbox: 收件箱名称 :param attachment_path: 附件路径 :param top: 一次读取几封邮件 :param mark_as_read: 标为已读邮件 :param only_unread: 查找未读邮件 :return: tuple(邮件对象,未读邮件总数) ''' # 邮件列表 mails = [] num = 1 inbox = ioutlook.get_inbox(mail_account, mail_inbox) if inbox: messages = inbox.Items if only_unread: messages = messages.Restrict('[UnRead] = True') # 未读取的邮件 messages.Sort("[ReceivedTime]", True) # 收件时间倒序 # 未读邮件总数 total_num = len(messages) if not top: top = len(messages) __logger.debug(u"total receive[" + str(len(messages)) + "]copies of mails,get Topn:" + str(top)) # 循环未读邮件 for message in messages: # 附件列表 atts = [] if num > top: break sender = message.SenderEmailAddress # 发件人地址 subject = message.Subject # 主题 body = message.Body # 正文 cc = message.CC # 抄送 received_time = str(message.ReceivedTime) # 收件时间 attachments = message.Attachments # 附件 # 判断主题是否存在 if subject_filter and subject_filter not in subject: continue else: flag = True # 如上,这里可以加多个判断条件,如:sender_filter、body_filter 等的过滤 # 循环附件 for attachment in attachments: file_name = attachment.FileName att_file_path = attachment_path + os.sep + file_name attachment.SaveAsFile(att_file_path) atts.append(att_file_path) if flag: mail_message = iresult.MailMessage() # 实例化 # 属性赋值 mail_message.sender_mail = sender mail_message.received_time = received_time mail_message.subject = subject mail_message.body = body mail_message.cc = cc mail_message.attachments = atts mails.append(mail_message) num += 1 if mark_as_read: message.UnRead = False # 标志为已读 print('附件:', atts) return mails, total_num # 循环接收符合条件的未读邮件,直到收取完毕 n = 1 while True: fp = r"C:\Users\Desktop\新建文件夹\附件%s" % n if not os.path.exists(fp): os.mkdir(fp) try: email, total_mail_num = recv_outlook('r95500@outlook.com', '测试', '收件箱', fp, 1) print('邮件对象:', email) print('邮件发件人:', email[0].sender_mail) print('邮件主题:', email[0].subject) print('邮件正文:', email[0].body) print('邮件总数:', total_mail_num) print('-' * 100) except IndexError: print('没有未读邮件') if total_mail_num <= 1: break n += 1
后续更新中。。。。