Created
October 8, 2013 16:11
-
-
Save christophlsa/6887169 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
from email.parser import Parser | |
import os, re, csv, argparse, sys | |
class EMailBounce(object): | |
def __init__(self, filename): | |
self.Delivery_status = {} | |
self.Recipient = '' | |
self.Reason = '' | |
self.Filename = filename | |
self.parse() | |
self.get_delivery_status() | |
self.get_infos() | |
def parse(self): | |
fp = open(self.Filename, mode='r', encoding='iso-8859-15') | |
self.msg = Parser().parse(fp) | |
fp.close() | |
def get_delivery_status(self): | |
self.Delivery_status = {} | |
if self.msg.is_multipart() and self.msg.get_content_type() == 'multipart/report': | |
for submsg in self.msg.get_payload(): | |
if submsg.get_content_type() == 'message/delivery-status': | |
for subsubmsg in submsg.get_payload(): | |
for item in subsubmsg.items(): | |
self.Delivery_status[item[0].lower()] = item[1] | |
def get_infos(self): | |
if 'original-recipient' in self.Delivery_status: | |
self.Recipient = self.Delivery_status['original-recipient'] | |
elif 'final-recipient' in self.Delivery_status: | |
self.Recipient = self.Delivery_status['final-recipient'] | |
self.Recipient = self.Recipient.replace('rfc822;', '').strip() | |
if 'diagnostic-code' in self.Delivery_status: | |
self.Reason = self.Delivery_status['diagnostic-code'].strip() | |
self.Reason = re.sub('^.+;', '', self.Reason) | |
self.Reason = re.sub('\s*\r?\n\s*', ' ', self.Reason) | |
parser = argparse.ArgumentParser(description='Geht die E-Mail Dateien im angegebenen Ordner durch, holt die E-Mail Adressen raus und speichert diese in eine CSV Datei.') | |
parser.add_argument('dir', help='Ordner mit den E-Mail Dateien.') | |
args = parser.parse_args() | |
rows = [] | |
if not os.path.exists(args.dir): | |
sys.stderr.write('Ordner existiert nicht\n') | |
exit(1) | |
for root, dirs, files in os.walk(args.dir): | |
for f in files: | |
em = EMailBounce(os.path.join(root, f)) | |
if em.Recipient.strip() == '': | |
print('failed: {}'.format(f)) | |
else: | |
rows.append({'email': em.Recipient, 'reason': em.Reason}) | |
csv.register_dialect('christophsdialect', delimiter=';', quotechar='"', lineterminator='\n', quoting=csv.QUOTE_MINIMAL) | |
with open('bounces.csv', 'w', newline='') as csvfile: | |
writer = csv.DictWriter(csvfile, ['email', 'reason'], dialect='christophsdialect') | |
writer.writerows(rows) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment