def clear_dead(self): try: now = time.time() for key, value in self.dict.items(): stay = now - value if stay > self.stay_seconds: del self.dict[key] self.update = True Logger.info('del self.dict[%s]' % key) return True except: Logger.error(traceback.format_exc()) return False
def handle(self): try: # 获取邮件唯一编号 mail_dict = self.get_new_mail_ids() # 依次处理所有邮件 for mail_idx, mail_id in mail_dict.items(): self.handle_one(mail_idx, mail_id) # recorder内存刷到磁盘 Logger.info("close sqlite") self.recorder.close() except: Logger.error(traceback.format_exc())
def __parse(self, e, leave): for item in e: rule = Rule(leave) for child in item: if child.tag == 'from': rule.from_address = child.text if child.tag == 'to': rule.to_address = child.text if child.tag == 'cc': rule.cc_address = child.text if child.tag == 'subject': rule.subject = child.text if child.tag == 'content': rule.content = child.text if leave: self.__leave.append(rule) else: self.__discard.append(rule) Logger.info(str(rule))
def loop_once(r_account, r_password, pop3_server, s_account, s_password, smpt_server, recorder_file, filter_file, send_flag, target_account, idx): """ :type r_account: str :type r_password: str :type pop3_server: str :type s_account: str :type s_password: str :type recorder_file: str :type filter_file: str :type smpt_server: str :type send_flag: bool :type target_account: str :type idx: int :return: """ try: # 打印标志 Logger.info("-----------------------%s--------------------------" % idx) # 初始化已读邮件记录 recorder = DBDict(recorder_file) # 初始化过滤策略 filters = Filter() if not filters.load(filter_file): Logger.error("init mail filter error") return False # 初始化邮件 proxy proxy = MailFilterProxy(r_account, r_password, pop3_server, s_account, s_password, smpt_server, recorder, filters, send_flag, target_account) proxy.handle() except: Logger.error(traceback.format_exc())
def send_mime(self, root): """ :type root: MIMEBase """ try: # 显示原始信息 for key in root.keys(): raw_header = 'old_key[%s] ====> [%s]' % (key, root.get(key)) Logger.info(raw_header) # 仅保留以下 Header left_header = ('from', 'boundary', 'content-type', 'mime-version', 'subject', 'date', 'message-id', 'content-transfer-encoding') for key in root.keys(): little = key.lower() if little not in left_header: del root[key] Logger.info("delete key[%s]" % key) root['to'] = self.target_account # 打印新key # for key in root.keys(): # raw_header = 'new_key[%s] ====> [%s]' % (key, root.get(key)) # Logger.info(raw_header) # 发送邮件 server = smtplib.SMTP(self.smpt_server, 25) server.login(self.s_account, self.s_password) server.sendmail(self.s_account, [self.target_account], root.as_string()) server.quit() except: Logger.error(traceback.format_exc())
def handle_one(self, mail_idx, mail_id): try: Logger.info("get mail[%s]" % mail_idx) resp, lines, octets = self.pop3_session.retr(mail_idx) msg_content = '\r\n'.join(lines) root = Parser().parsestr(msg_content) # 记录邮件 self.recorder.put(mail_id) # 解析邮件 mail_info = self.parse_mail(root) if not mail_info: return # 过滤邮件 msg = "idx[{}], id[{}], from[{}], to[{}], cc[{}], subject[{}]". \ format(mail_idx, mail_id, mail_info.from_address, mail_info.to_address, mail_info.cc_address, mail_info.subject) if not self.filters.filter(mail_info): Logger.report("filter: " + msg) return # 发送邮件 Logger.report("send: " + msg) if self.send_flag: self.send_mime(root) else: Logger.report(mail_info.content) except: Logger.error(traceback.format_exc())
def __main__(): # utf-8 reload(sys) sys.setdefaultencoding('utf-8') # 日志目录 log_target = "logs" # 邮件过滤策 filter_file = "config/filter.xml" # 收件账号 r_account = raw_input("receive mail account: ") # 收件密码 r_password = getpass.getpass('receive mail password: '******'send mail password: '******'receive mail password: '******'send mail password: '******'Y' and input_flag != 'N': print >> sys.stderr, "Invalid send_flag values, it must be Y or N" return False send_flag = True if input_flag == 'Y' else False print >> sys.stdout, "program is running in background, please check the running log!" # 初始化日志 Logger.init(LogEnv.develop, log_target, "result", max_file_count=10) Logger.info("program is starting......") # 非调试状态时在后台启动 try: pid = os.fork() if pid > 0: Logger.info("#1 parent exit") os._exit(0) except: Logger.error(traceback.format_exc()) try: pid = os.fork() if pid > 0: Logger.info("#2 parent exit") Logger.info("pid[%s] is running..." % pid) os._exit(0) except: Logger.error(traceback.format_exc()) # 邮件记录文件 self_dir = os.path.dirname(os.path.abspath(__file__)) recorder_dir = os.path.join(self_dir, 'data') if not os.path.exists(recorder_dir): os.mkdir(recorder_dir) recorder_file = os.path.join(self_dir, 'data', 'transfer.db') # 循环接收邮件 idx = 0 while True: try: loop_once(r_account, r_password, pop3_server, s_account, s_password, smpt_server, recorder_file, filter_file, send_flag, target_account, idx) idx += 1 # 非调试状态时循环转发邮件 time.sleep(60) # 调试用 # break except: Logger.error(traceback.format_exc())