接收outlook邮件时可以多条件过滤
作者:互联网
在使用outlook接收邮件的时候,我们可能会遇到这种情况,需要对主题或者附件进行过滤,但是过滤条件可能不止一个,这时RPA的ioutlook函数,可能不是很好使,所以自己就根据源码对过滤进行了简单的升级和优化。
def recv_outlook(mail_account, mail_inbox='收件箱', sender_filter=None, subject_filter=None, attachments_filter=None, attachment_path=None, mark_as_read=True, only_unread=True, top=1): ''' :param mail_account: 邮箱账号 :param mail_inbox: 收件箱名称 :param sender_filter 发件人过滤条件 :param subject_filter: 主题过滤条件 :param attachments_filter: 附件过滤条件 :param attachment_path: 附件路径 :param mark_as_read: 标为已读邮件 :param only_unread: 查找未读邮件 :param top: 一次读取几封邮件 :return: tuple(邮件对象列表,邮件状态, 附件列表) ''' # 邮件列表 mails = [] num = 1 file_names = [] state = False 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) # 收件时间倒序 if not top: top = len(messages) # 循环未读邮件 for message in messages: # 附件列表 atts = [] if num > top: break sender = message.SenderName # 发件人名字 sender_addr = message.SenderEmailAddress # 发件人地址 subject = message.Subject # 主题 body = message.Body # 正文 cc = message.CC # 抄送 received_time = str(message.ReceivedTime) # 收件时间 attachments = message.Attachments # 附件 # 发件人过滤 if sender_filter and sender_filter not in sender: continue else: state = True # 主题过滤 if subject: for sub in subject_filter: if sub and sub in subject: state = True # 附件过滤 if len(attachments) > 0: if attachments_filter and len(attachments) > 0: for attachment in attachments: file_name = attachment.FileName file_names.append(file_name) k = 0 for att in attachments_filter: if att and att in file_name: state = True if not attachment_path: attachment_path = __attachment_path att_file_path = attachment_path + os.sep + file_name attachment.SaveAsFile(att_file_path) atts.append(att_file_path) k += 1 else: if k == 0: state = False # 无附件将邮件标记为已读 if mark_as_read: message.UnRead = False else: # 无附件将邮件标记为已读 if mark_as_read: message.UnRead = False continue if state: mail_message = iresult.MailMessage() # 实例化 # 属性赋值 mail_message.sender = sender mail_message.sender_mail = sender_addr 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 # 标志为已读 return mails, state, file_names res = recv_outlook('test', subject_filter=['test', '测试'], sender_filter='test', attachments_filter=['测试', '小米'], attachment_path=r"C:\Users\Desktop\")
''' res: ([], False, []) res[1]为True:有邮件被接收,但是可能主题不符或该邮件无附件 '''
标签:outlook,sender,filter,过滤,mail,message,邮件,attachments 来源: https://www.cnblogs.com/rongge95500/p/11613392.html