def run(self): """Start listening for incoming emails""" _print("Listening for incoming emails on {}:{} ...".format(*self.addr)) if not self.timeout: asyncore.loop() else: asyncore.loop(timeout=1, count=self.timeout)
def __init__(self, addr=None, remote_addr=None, debug=False, timeout=None, **kwargs): super().__init__(addr, remote_addr) self.debug = debug self.timeout = timeout self.processors = defaultdict(lambda: {}) _print("Created SMTP server <{}:{}>".format(addr[0], addr[1]))
def process_attachment(self, payload, filename): s3key = self.get_s3key(payload) self.client.put_object(ACL='private', Bucket=self.bucket, Body=payload, Key=s3key) _print("Produced {}".format(s3key))
def process_attachment(self, payload, filename, **params): if not os.path.isdir(self.directory): os.makedirs(self.directory) target_file = os.path.join(self.directory, filename) with open(target_file, 'wb') as fp: fp.write(payload) _print("Saved {}".format(target_file))
def process_message(self, peer, mailfrom, rcpttos, data): """Some generic processing common to all server""" recipient = rcpttos[0].split('@')[0] _print("Receiving email from {} ({})".format(mailfrom, peer)) username, params = self._process_recipient(recipient) if username in self.processors: _print("Processing ...") for proc in self.processors[username].values(): _print("Running {} processor ...".format(proc.name)) proc.process(peer, mailfrom, rcpttos, data, **params) _print("Done!") else: _print("No processors registered for {}".format(username))
def get_s3key(self, payload): """Produces a meaningful S3 key based on the report properties: reporting period, reporting account, etc""" with ZipFile(io.BytesIO(payload)) as myzip: # Should contain just one file: the report file = myzip.filelist[0] msg = "Processing {}, created on {}-{}-{} {}:{}:{}".format( file.filename, *file.date_time) _print(msg) with myzip.open(file.filename, 'r') as myfile: hdr = self._process_header(myfile) unknown_account = "unknown-{}".format(uuid.uuid4()) account = filename_from_string(hdr.account or unknown_account) return os.path.join(self.prefix, hdr.type.lower(), str(hdr.first_day.year), str(hdr.first_day.month), str(hdr.first_day.day), account + '.tsv.zip')
def process(self, peer, mailfrom, rcpttos, data, **params): """Prints summary stats of the email""" _print("Receiving message from: {}".format(peer)) _print("Message addressed from: {}".format(mailfrom)) _print("Message addressed to : {}".format(rcpttos)) _print("Message length : {}".format(len(data)))
def register_processor(self, username, *processors): """Registers one ore more processor with a username""" for proc in processors: _print("Registered {} on {}".format(proc.name, username)) self.processors[username][proc.name] = proc