diff --git a/.gitignore b/.gitignore index dbe25ad..e693d67 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,8 @@ - *.pyc +*.html + +/.idea/* +/.git/* /__pycache__/* +/Mail_Push_Core/__pycache__/* /dist/* \ No newline at end of file diff --git a/BIT_Mail.py b/BIT_Mail.py index 0bc4a6a..fd18ebb 100644 --- a/BIT_Mail.py +++ b/BIT_Mail.py @@ -4,11 +4,12 @@ from apscheduler.triggers.cron import CronTrigger import warnings -from Mail_Push_Core.keywds_cache import kc_delete +from Mail_Push_Core.keywds_cache import cache_delete +from Mail_Push_Core.myprint import myprint warnings.filterwarnings("ignore") -from Mail_Push_Core.Wechat_push import push_config +from Mail_Push_Core.Pushing import push_config from Mail_Push_Core.file_select_GUI import file_select_GUI from Mail_Push_Core.monitor_config import monitor_config from Mail_Push_Core.mail_keywds import keywds_monitor @@ -36,10 +37,10 @@ def main(): BIT_mail = imaplib.IMAP4(host=Imap_url, port=Port) try: BIT_mail.login(User, Passwd) - print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 验证成功,账户密码正确,定时任务已启动') + myprint(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 验证成功,登录信息正确,定时任务已启动') except Exception as e: - print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 验证失败,请重新检查登录信息') - print("ErrorType : {}, Error : {}".format(type(e).__name__, e)) + myprint(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 验证失败,请重新检查登录信息') + myprint("ErrorType : {}, Error : {}".format(type(e).__name__, e)) BIT_mail.logout() scheduler = BlockingScheduler(timezone="Asia/Shanghai") @@ -50,7 +51,7 @@ def main(): scheduler.add_job(keywds_monitor, trigger_Keywords, max_instances=5, args=[Imap_url, Port, User, Passwd, Date_range, Keywords_raw, Sendkeys]) trigger_kc_delete = CronTrigger(hour='02', minute='03') # 缓存清理时间,每天凌晨2点 - scheduler.add_job(kc_delete, trigger_kc_delete, max_instances=5) + scheduler.add_job(cache_delete, trigger_kc_delete, max_instances=5) # 添加邮件汇总推送任务 trigger_mail_summary = CronTrigger(hour=hour_summary, minute=minute_summary, second='30') scheduler.add_job(mail_summary, trigger_mail_summary, max_instances=5, @@ -58,6 +59,10 @@ def main(): # 启动任务 scheduler.start() + # 调试使用 + # keywds_monitor(Imap_url, Port, User, Passwd, Date_range, Keywords_raw, Sendkeys) + # mail_summary(Imap_url, Port, User, Passwd, Date_range, Sendkeys) + if __name__ == '__main__': main() diff --git a/Mail_Push_Core/Pushing.py b/Mail_Push_Core/Pushing.py new file mode 100644 index 0000000..ae95eeb --- /dev/null +++ b/Mail_Push_Core/Pushing.py @@ -0,0 +1,76 @@ +import requests +import json +import configparser + +from Mail_Push_Core.Wechat import WeChat +from Mail_Push_Core.myprint import myprint +# 打包exe +import os +import sys + +os.environ['REQUESTS_CA_BUNDLE'] = os.path.join(os.path.dirname(sys.argv[0]), 'cacert.pem') + + +def push_config(config_filename): + config_data = configparser.ConfigParser() + config_data.read(config_filename, encoding='utf-8') + + my_push_url = config_data.get('Sendkey', 'my_push_url') + push_plus_sendkey = config_data.get('Sendkey', 'push_plus_sendkey') + CORPID = config_data.get('Sendkey', 'QYWX_CORPID') + CORPSECRET = config_data.get('Sendkey', 'QYWX_CORPSECRET') + agentid = config_data.get('Sendkey', 'QYWX_agentid') + + return [my_push_url, push_plus_sendkey, [CORPID, CORPSECRET, agentid]] + + +def push(Pushing_Data, Sendkeys): + # 自建通道 + if Sendkeys[0] != '': + # 将url改为自建地址 + my_Pushing_Data = Pushing_Data.replace("\n", "%0D%0A") + my_url = Sendkeys[0] + my_Pushing_Data + my_send_info = requests.get(my_url) + if "\"errmsg\":\"ok\"" in str(my_send_info.content, encoding="utf-8"): + myprint('自建通道已推送') + else: + myprint('自建通道推送超时') + else: + pass + # myprint('未配置自建通道推送') + + # PushPlus通道"msg":"请求成功" + if Sendkeys[1] != '': + pushplus_token = Sendkeys[1] + pushplus_title = '北理工邮箱推送' + pushplus_template = 'html' + pushplus_url = 'http://www.pushplus.plus/send' + pushplus_data = { + "token": pushplus_token, + "title": pushplus_title, + "content": Pushing_Data, + "template": pushplus_template + } + pushplus_body = json.dumps(pushplus_data).encode(encoding='utf-8') + pushplus_headers = {'Content-Type': 'application/json'} + pushplus_send_info = requests.post(pushplus_url, data=pushplus_body, headers=pushplus_headers) + + if "\"msg\":\"请求成功\"" in str(pushplus_send_info.content, encoding="utf-8"): + myprint('PushPlus通道已推送') + else: + myprint('PushPlus通道推送超时') + else: + pass + + if Sendkeys[2][0] != '': + qywx = WeChat() + qywx.CORPID = Sendkeys[2][0] + qywx.CORPSECRET = Sendkeys[2][1] + qywx.agentid = Sendkeys[2][2] + qywx_send_info = qywx.send_text(Pushing_Data) + if qywx_send_info: + myprint('企业微信通道已推送') + else: + myprint('企业微信通道推送超时') + else: + pass diff --git a/Mail_Push_Core/Wechat.py b/Mail_Push_Core/Wechat.py new file mode 100644 index 0000000..a0f0213 --- /dev/null +++ b/Mail_Push_Core/Wechat.py @@ -0,0 +1,64 @@ +import os +import time +import requests +import json + + +class WeChat: + def __init__(self): + self.CORPID = "" # 企业ID,在管理后台获取 + self.CORPSECRET = "" # 自建应用的Secret,每个自建应用里都有单独的secret + self.agentid = "" + self.touser = "@all" + + def _get_access_token(self): # 获取access_token + url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken' + values = {'corpid': self.CORPID, # 企业ID, + 'corpsecret': self.CORPSECRET, # 应用的Secret + } + req = requests.post(url, params=values) + data = json.loads(req.text) + return data["access_token"], data["expires_in"] + + def get_access_token(self): + cur_time = time.time() # 获取现在的时间 + if not os.path.isdir('./cache'): + os.makedirs('./cache') + try: + with open('./cache/access_token.conf', 'r') as f: + t, expires_in, access_token = f.read().split() # 读取文件中的t即上次获取access token的时间和access token的值 + if 0 < cur_time - float(t) < float(expires_in): # 判断access token是否在有效期内 + return access_token # 如果在,则返回读取的access token + else: # 否则,先打开文件,权限可以编辑 + with open('./cache/access_token.conf', 'w') as f: + access_token, expires_in = self._get_access_token() # 获取access token + f.write('\t'.join([str(cur_time), str(expires_in), access_token])) # 把获取到的Access token和当前时间写入文件 + return access_token # 返回access token的值 + + except: # 如果是第一次运行,则运行此语句,获取access token的值 + with open('./cache/access_token.conf', 'w') as f: + access_token, expires_in = self._get_access_token() + cur_time = time.time() + f.write('\t'.join([str(cur_time), str(expires_in), access_token])) + return access_token + + def send_text(self, _message): + access_token = self.get_access_token() + json_dict = { + "touser": self.touser, + "msgtype": "text", + "agentid": self.agentid, + "text": { + "content": _message + }, + "safe": 0, + "enable_id_trans": 1, + "enable_duplicate_check": 0, + "duplicate_check_interval": 1800 + } + json_str = json.dumps(json_dict) + response_send = requests.post( + "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}".format( + access_token=access_token), data=json_str) + # print("send to " + useridstr + ' ' + json.loads(response_send.text)['errmsg']) + return json.loads(response_send.text)['errmsg'] == 'ok' diff --git a/Mail_Push_Core/Wechat_push.py b/Mail_Push_Core/Wechat_push.py deleted file mode 100644 index 2899519..0000000 --- a/Mail_Push_Core/Wechat_push.py +++ /dev/null @@ -1,44 +0,0 @@ -import requests -import configparser -# 打包exe -import os -import sys -os.environ['REQUESTS_CA_BUNDLE'] = os.path.join(os.path.dirname(sys.argv[0]), 'cacert.pem') - - -def push_config(config_filename): - config_data = configparser.ConfigParser() - config_data.read(config_filename, encoding='utf-8') - - my_push_url = config_data.get('Sendkey', 'my_push_url') - push_plus_sendkey = config_data.get('Sendkey', 'push_plus_sendkey') - - return [my_push_url, push_plus_sendkey] - - -def push(Pushing_Data, Sendkeys): - # 自建通道 - if Sendkeys[0] != '': - # 将url改为自建地址 - my_Pushing_Data = Pushing_Data.replace("\n", "%0D%0A") - url = Sendkeys[0] + my_Pushing_Data - send_info = requests.get(url) - if "\"errmsg\":\"ok\"" in str(send_info.content, encoding = "utf-8"): - print('自建通道已推送') - else: - print('自建通道推送超时') - else: - pass - # print('未配置自建通道推送') - - # PushPlus通道"msg":"请求成功" - if Sendkeys[1] != '': - url = 'http://www.pushplus.plus/send?token=' + Sendkeys[ - 1] + '&title=北理工邮箱推送&content=' + Pushing_Data + '&template=txt' - send_info = requests.get(url) - if "\"msg\":\"请求成功\"" in str(send_info.content, encoding="utf-8"): - print('PushPlus通道已推送') - else: - print('PushPlus通道推送超时') - else: - pass diff --git a/Mail_Push_Core/__pycache__/keywds_cache.cpython-39.pyc b/Mail_Push_Core/__pycache__/keywds_cache.cpython-39.pyc index 4775e42..4aaa693 100644 Binary files a/Mail_Push_Core/__pycache__/keywds_cache.cpython-39.pyc and b/Mail_Push_Core/__pycache__/keywds_cache.cpython-39.pyc differ diff --git a/Mail_Push_Core/__pycache__/mail_keywds.cpython-39.pyc b/Mail_Push_Core/__pycache__/mail_keywds.cpython-39.pyc index d083413..70762e0 100644 Binary files a/Mail_Push_Core/__pycache__/mail_keywds.cpython-39.pyc and b/Mail_Push_Core/__pycache__/mail_keywds.cpython-39.pyc differ diff --git a/Mail_Push_Core/__pycache__/mail_login.cpython-39.pyc b/Mail_Push_Core/__pycache__/mail_login.cpython-39.pyc index 2f93724..057d991 100644 Binary files a/Mail_Push_Core/__pycache__/mail_login.cpython-39.pyc and b/Mail_Push_Core/__pycache__/mail_login.cpython-39.pyc differ diff --git a/Mail_Push_Core/__pycache__/mail_summary.cpython-39.pyc b/Mail_Push_Core/__pycache__/mail_summary.cpython-39.pyc index 2af825a..55b9e05 100644 Binary files a/Mail_Push_Core/__pycache__/mail_summary.cpython-39.pyc and b/Mail_Push_Core/__pycache__/mail_summary.cpython-39.pyc differ diff --git a/Mail_Push_Core/keywds_cache.py b/Mail_Push_Core/keywds_cache.py index cb5e4a5..24afbf4 100644 --- a/Mail_Push_Core/keywds_cache.py +++ b/Mail_Push_Core/keywds_cache.py @@ -1,8 +1,12 @@ import os +from Mail_Push_Core.myprint import myprint + def kc_save(data): - with open('cache.txt', 'w') as f: + if not os.path.isdir('./cache'): + os.makedirs('./cache') + with open('./cache/cache.txt', 'w') as f: for value in data: f.write(str(value)) f.write('\n') @@ -11,7 +15,9 @@ def kc_save(data): def kc_load(): new_data = [] try: - with open('cache.txt', 'r') as f: + if not os.path.isdir('./cache'): + os.makedirs('./cache') + with open('./cache/cache.txt', 'r') as f: data = list(f) for value in data: new_value = value.replace('\n', '') @@ -21,14 +27,14 @@ def kc_load(): return new_data -def kc_delete(): +def cache_delete(): try: - os.remove('cache.txt') - print(' ---------------------------------') - print(' | |') - print(' | 关键词缓存已清理 |') - print(' | 关键词缓存已清理 |') - print(' | |') - print(' ---------------------------------') + os.remove('./cache/cache.txt') + os.remove('./cache/print_cache.txt') + myprint(' ---------------------------------') + myprint(' | |') + myprint(' | 关键词缓存与打印缓存已清理 |') + myprint(' | |') + myprint(' ---------------------------------') except: pass diff --git a/Mail_Push_Core/mail_keywds.py b/Mail_Push_Core/mail_keywds.py index 1d3d610..c438231 100644 --- a/Mail_Push_Core/mail_keywds.py +++ b/Mail_Push_Core/mail_keywds.py @@ -1,13 +1,16 @@ +import base64 import datetime import email +import quopri +import re import time from email.header import decode_header, make_header import jieba -from Mail_Push_Core.Wechat_push import push +from Mail_Push_Core.Pushing import push from Mail_Push_Core.mail_login import mail_login - from Mail_Push_Core.keywds_cache import kc_load, kc_save +from Mail_Push_Core.myprint import myprint jieba.setLogLevel(20) """ @@ -21,29 +24,47 @@ """ +def encoded_words_to_text(encoded_words): + encoded_word_regex = r'=\?{1}(.+)\?{1}([B|Q])\?{1}(.+)\?{1}=' + try: + text = str(make_header(decode_header(encoded_words))) + except: + try: + charset, encoding, encoded_text = re.match(encoded_word_regex, encoded_words).groups() + if encoding == 'B': + byte_string = base64.b64decode(encoded_text) + text = byte_string.decode(charset) + elif encoding == 'Q': + byte_string = quopri.decodestring(encoded_text) + text = byte_string.decode(charset) + except: + text = '无主题' + return text + + def keywds_monitor(Imap_url, Port, User, Passwd, Date_range, Keywords_raw, Sendkeys): - print('---------------------------------------------------------') - print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 关键词监测任务开始运行') + myprint('---------------------------------------------------------') + myprint(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 关键词监测任务开始运行') BIT_mail = mail_login(Imap_url, Port, User, Passwd) try: BIT_mail.select(mailbox='INBOX', readonly=True) - print('Mailbox selected.') + myprint('Mailbox selected.') except Exception as e: - print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' Select失败') - print("ErrorType : {}, Error : {}".format(type(e).__name__, e)) + myprint(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' Select失败') + myprint("ErrorType : {}, Error : {}".format(type(e).__name__, e)) date = datetime.date.today().strftime("%d-%b-%Y") if int(Date_range) == 1 else ( datetime.date.today() - datetime.timedelta(days=int(Date_range))).strftime("%d-%b-%Y") _, data = BIT_mail.search(None, '(ALL)', f'(SENTSINCE {date})') if data[0] is None: - print('今日未收到邮件') if int(Date_range) == 1 else print('%s日内未收到邮件' % Date_range) - print('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') + myprint('今日未收到邮件') if int(Date_range) == 1 else myprint('%s日内未收到邮件' % Date_range) + myprint('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') else: - print('今日已收到%d封邮件 - %s' % (len(data[0].split()), User)) if int(Date_range) == 1 else print( + myprint('今日已收到%d封邮件 - %s' % (len(data[0].split()), User)) if int(Date_range) == 1 else myprint( '%s日内已收到%d封邮件 - %s' % (Date_range, len(data[0].split()), User)) - print('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') + myprint('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') msgs = [] for num in data[0].split(): typ, mail_data = BIT_mail.fetch(num, '(RFC822)') @@ -58,9 +79,9 @@ def keywds_monitor(Imap_url, Port, User, Passwd, Date_range, Keywords_raw, Sendk my_msg = email.message_from_bytes(msg[0][1]) Message_ID = my_msg['Message-ID'] - Subject_raw = str(make_header(decode_header(my_msg['Subject']))) + Subject_raw = encoded_words_to_text(my_msg['Subject']) Subject = Subject_raw.replace('\r\n', '').replace('\n', '') - print(str(Email_count) + ' -- ' + Subject) + myprint(str(Email_count) + ' -- ' + Subject) Email_count += 1 if Message_ID in keywds_cache: @@ -69,12 +90,12 @@ def keywds_monitor(Imap_url, Port, User, Passwd, Date_range, Keywords_raw, Sendk keywds_cache.append(Message_ID) From = str(make_header(decode_header(my_msg['From']))) - To = str(make_header(decode_header(my_msg['To']))) + # To = str(make_header(decode_header(my_msg['To']))) Date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(email.utils.mktime_tz(email.utils.parsedate_tz(my_msg['Date'])))) # Date = str(make_header(decode_header(my_msg['date']))) - Single_Email = f"主题: {Subject}" + "\n" + f"发件人: {From}" + "\n" + f"收件人: {To}" + "\n" + f"日期: {Date}" + Single_Email = f"主题: {Subject}" + "\n" + f"发件人: {From}" + "\n" + f"日期: {Date}" words = jieba.lcut(Single_Email.lower(), cut_all=True) Keywords = jieba.lcut(Keywords_raw.lower(), cut_all=False) @@ -88,22 +109,23 @@ def keywds_monitor(Imap_url, Port, User, Passwd, Date_range, Keywords_raw, Sendk for keywd in Keywords: if keywd.lower() in words: keywd_flag = 1 - Single_Data = r'邮件监测 - 关键词:' + keywd.lower() + r'%0D%0A推送时间:' + datetime.datetime.now().strftime( - '%Y-%m-%d %H:%M:%S') + '\n-----------------------------------\n' + Single_Email + '\n***********************************\n' + Single_Data = Single_Email + '\n******************************\n' All_Data = All_Data + Single_Data - All_Keywds = All_Keywds + ' / ' + keywd.lower() + All_Keywds = All_Keywds + '/' + keywd.lower() break kc_save(keywds_cache) - print('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') + myprint('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') if keywd_flag == 1: - print('已监测到关键词:' + All_Keywds) + myprint('已监测到关键词:' + All_Keywds) + All_Data = f"监测邮箱: {User}" + '\n' + '关键词 - ' + All_Keywds + '\n' + '推送时间:' + datetime.datetime.now().strftime( + '%Y-%m-%d %H:%M:%S') + '\n------------------------------\n' + All_Data push(All_Data, Sendkeys) else: - print('未收到关键词相关邮件或已推送,继续自动监测') + myprint('未收到关键词相关邮件或已推送,继续自动监测') BIT_mail.close() - print('Mailbox closed.') + myprint('Mailbox closed.') BIT_mail.logout() - print('退出登录') - print('*********************************************************') + myprint('退出登录') + myprint('*********************************************************') diff --git a/Mail_Push_Core/mail_login.py b/Mail_Push_Core/mail_login.py index ea27fb6..4447575 100644 --- a/Mail_Push_Core/mail_login.py +++ b/Mail_Push_Core/mail_login.py @@ -1,6 +1,8 @@ import datetime import imaplib +from Mail_Push_Core.myprint import myprint + def mail_login(Imap_url, Port, User, Passwd): global BIT_mail @@ -8,9 +10,9 @@ def mail_login(Imap_url, Port, User, Passwd): BIT_mail = imaplib.IMAP4(host=Imap_url, port=Port) if Port == 143 else imaplib.IMAP4_SSL(host=Imap_url, port=Port) BIT_mail.login(User, Passwd) - print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 重登录成功') + myprint(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 重登录成功') except Exception as e: - print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 重登录失败') - print("ErrorType : {}, Error : {}".format(type(e).__name__, e)) + myprint(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 重登录失败') + myprint("ErrorType : {}, Error : {}".format(type(e).__name__, e)) return BIT_mail diff --git a/Mail_Push_Core/mail_summary.py b/Mail_Push_Core/mail_summary.py index 7340a2e..5387d1d 100644 --- a/Mail_Push_Core/mail_summary.py +++ b/Mail_Push_Core/mail_summary.py @@ -3,8 +3,10 @@ import time from email.header import decode_header, make_header -from Mail_Push_Core.Wechat_push import push +from Mail_Push_Core.Pushing import push +from Mail_Push_Core.mail_keywds import encoded_words_to_text from Mail_Push_Core.mail_login import mail_login +from Mail_Push_Core.myprint import myprint """ Imap_url:IMAP服务地址 @@ -17,42 +19,41 @@ def mail_summary(Imap_url, Port, User, Passwd, Date_range, Sendkeys): - print('---------------------------------------------------------') - print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 邮件汇总任务开始运行') + myprint('---------------------------------------------------------') + myprint(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 邮件汇总任务开始运行') BIT_mail = mail_login(Imap_url, Port, User, Passwd) try: BIT_mail.select(mailbox='INBOX', readonly=True) - print('Mailbox selected.') + myprint('Mailbox selected.') except Exception as e: - print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' Select失败') - print("ErrorType : {}, Error : {}".format(type(e).__name__, e)) + myprint(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' Select失败') + myprint("ErrorType : {}, Error : {}".format(type(e).__name__, e)) date = datetime.date.today().strftime("%d-%b-%Y") if int(Date_range) == 1 else ( datetime.date.today() - datetime.timedelta(days=int(Date_range))).strftime("%d-%b-%Y") _, data = BIT_mail.search(None, '(ALL)', f'(SENTSINCE {date})') if data[0] is None: - print('今日未收到邮件') if int(Date_range) == 1 else print('%s日内未收到邮件' % Date_range) - print('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') + myprint('今日未收到邮件') if int(Date_range) == 1 else myprint('%s日内未收到邮件' % Date_range) + myprint('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') else: - print('今日已收到%d封邮件 - %s' % (len(data[0].split()), User)) if int(Date_range) == 1 else print( + myprint('今日已收到%d封邮件 - %s' % (len(data[0].split()), User)) if int(Date_range) == 1 else myprint( '%s日内已收到%d封邮件 - %s' % (Date_range, len(data[0].split()), User)) - print('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') + myprint('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') msgs = [] for num in data[0].split(): typ, mail_data = BIT_mail.fetch(num, '(RFC822)') msgs.append(mail_data) - # All_Data = r'今日共收到邮件' + str(len(data[0].split())) + '封-' + User + '\n' All_Data = r'今日共收到邮件' + str(len(data[0].split())) + '封\n' + User + '\n' if int( Date_range) == 1 else Date_range + r'日内共收到邮件' + str( len(data[0].split())) + '封\n' + User + '\n' - for msg in msgs[::-1]: + for msg in msgs: my_msg = email.message_from_bytes(msg[0][1]) - Subject_raw = str(make_header(decode_header(my_msg['Subject']))) - Subject = Subject_raw.replace('\r\n', '') + Subject_raw = encoded_words_to_text(my_msg['Subject']) + Subject = Subject_raw.replace('\r\n', '').replace('\n', '') From = str(make_header(decode_header(my_msg['From']))) # To = str(make_header(decode_header(my_msg['To']))) Date = time.strftime("%Y-%m-%d %H:%M:%S", @@ -65,9 +66,9 @@ def mail_summary(Imap_url, Port, User, Passwd, Date_range, Sendkeys): push(All_Data, Sendkeys) - print('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') + myprint('<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>') BIT_mail.close() - print('Mailbox closed.') + myprint('Mailbox closed.') BIT_mail.logout() - print('退出登录') - print('*********************************************************') + myprint('退出登录') + myprint('*********************************************************') diff --git a/Mail_Push_Core/myprint.py b/Mail_Push_Core/myprint.py new file mode 100644 index 0000000..7a70090 --- /dev/null +++ b/Mail_Push_Core/myprint.py @@ -0,0 +1,9 @@ +import os + + +def myprint(data): + print(data) + if not os.path.isdir('./cache'): + os.makedirs('./cache') + with open('./cache/print_cache.txt', 'a') as f: + print(data, file=f) diff --git a/config_template.ini b/config_template.ini index 2177487..6578e9a 100644 --- a/config_template.ini +++ b/config_template.ini @@ -8,10 +8,17 @@ Keywords = keyword ; 推送通道设置 [Sendkey] -push_plus_sendkey = d7f46sdagdfa +my_push_url = https://your.push.com/?sendkey= +push_plus_sendkey = ; push_plus_sendkey获取方法见官网 ; http://www.pushplus.plus/ -my_push_url = https://your.push.com/?sendkey= +QYWX_CORPID = +QYWX_CORPSECRET = +QYWX_agentid = +; 企业微信配置,请参考官方文档 +; https://developer.work.weixin.qq.com/document/path/90487 +; https://developer.work.weixin.qq.com/document/path/90236#10167 + ; 以下设置如果不明白含义就先别改了 ; 北理工邮箱IMAP服务地址