Postankuendigung/Postankuendigung.py

62 lines
2 KiB
Python

from imap_tools import MailBox
import os
import sys
import json
import telebot
def conf():
appname = os.path.basename(sys.argv[0])
appname = appname.replace(".py", ".conf")
absFilePath = os.path.abspath(__file__)
absFilePath = absFilePath.replace(".py", ".conf")
if os.path.isfile(absFilePath) is False:
print(appname + ' scheint es nicht zu geben.')
print('Ich lege eine neue Datei ' + appname + ' an.')
passw = {'mail':
{
"mail_pass": "",
"mail_user": "",
"mail_host": "",
"mail_folder": ""
},
'Telegram':
{
"Chat_ID": "",
"TOKEN": ""
}
}
print(str(appname) + ' bitte entsprechend befüllen.')
with open(absFilePath, 'w') as fp:
json.dump(passw, fp, sort_keys=True, indent=4)
quit()
else:
with open(absFilePath) as file:
passw = json.load(file)
return passw
passw = conf()
telegram_chat_id = passw['Telegram']['Chat_ID']
telegram_token = passw['Telegram']['TOKEN']
tb = telebot.TeleBot(telegram_token)
host = passw['mail']['mail_host']
username = passw['mail']['mail_user']
password = passw['mail']['mail_pass']
folder = passw['mail']['mail_folder']
with MailBox(host).login(username, password, folder) as mailbox:
anzahl = len(mailbox.numbers(criteria='UNSEEN'))
ankuendigung = 'Heute befinden sich ' + str(anzahl) + ' Sendungen auf dem Weg in die Hintergasse.'
tb.send_message(telegram_chat_id, ankuendigung)
for msg in mailbox.fetch(mark_seen=True,criteria='UNSEEN' ): #criteria='UNSEEN'
for att in msg.attachments:
fn = att.filename
ext = (att.content_type[-3:])
fn = str(msg.uid) + fn +'.'+ ext
with open(fn, 'wb') as f:
f.write(att.payload)
document = open(fn, 'rb')
tb.send_document(telegram_chat_id, document, caption=msg.date)
os.remove(fn)