From 8bc5222692a134acb75bf3731ea1e43248177468 Mon Sep 17 00:00:00 2001 From: Maximilian Friedersdorff Date: Fri, 14 Sep 2018 09:47:17 +0100 Subject: [PATCH 1/1] Initial commit --- .gitignore | 2 ++ requirements.txt | 2 ++ syndicate.py | 83 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+) create mode 100644 .gitignore create mode 100644 requirements.txt create mode 100644 syndicate.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b7164c9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +account +venv diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..12305e4 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +python-dateutil==2.7.3 +six==1.11.0 diff --git a/syndicate.py b/syndicate.py new file mode 100644 index 0000000..ea9b331 --- /dev/null +++ b/syndicate.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python + +import imaplib +import smtplib +import datetime +from email.parser import BytesParser +from email.message import EmailMessage +from email.policy import default + +from dateutil import parser + +def process_mailbox(M): + rv, data = M.search(None, 'UNSEEN') + if rv != 'OK': + print('Failed to search for UNSEEN messages') + return [], -1 + + mails = [] + n_failures = 0 + for num in data[0].split(): + rv, data = M.fetch(num, '(RFC822)') + if rv != 'OK': + print('Error fetching message from server: {}'.format(num)) + n_failures += 1 + + msg = BytesParser(policy=default).parsebytes(data[0][1]) + mails.append({ + 'date': msg['Date'], + 'subject': msg['Subject'] + }) + + return mails, n_failures + +M = imaplib.IMAP4_SSL('outlook.office365.com') +mailboxes = ['Notifications/NPPC/Updates', 'Notifications/NPPC/Uptime', 'Notifications/NPPC/Icinga'] +credential_file = './account' + +creds = None +with open(credential_file) as f: + creds = f.readlines() + +creds = [line.rstrip('\n') for line in creds] + +try: + M.login(creds[0], creds[1]) +except imaplib.IMAP4.error: + print('Login Failed') + exit(1) + +all_messages = {} + +for box in mailboxes: + rv, data = M.select(box) + if rv != 'OK': + print('Failed to open {}'.format(box)) + exit(1) + + + all_messages[box] = process_mailbox(M) + +email_content = [] +for box, messages in all_messages.items(): + + ms = sorted(messages[0], + key=lambda m: parser.parse(m['date'])) + + content = '{} failures to fetch messages in {}\n'.format(messages[1], box) + ms = ["{}: {}".format(m['date'], m['subject']) + for m in ms] + content += '\n'.join(ms) + email_content.append(content) + +email_content = '\n\n'.join(email_content) + +summary = EmailMessage() +summary.set_content(email_content) +summary['Subject'] = datetime.datetime.now().strftime('Summary of emails on %c') +summary['From'] = 'maf54@aber.ac.uk' +summary['To'] = 'maf54@aber.ac.uk' + +s = smtplib.SMTP('smtphost.aber.ac.uk') +s.sendmail('maf54@aber.ac.uk', 'maf54@aber.ac.uk', summary.as_string()) +s.quit() -- 2.46.2