"""Netscape Messaging Server bounce formats.
I've seen at least one NMS server version 3.6 (envy.gmp.usyd.edu.au) bounce
messages of this format. Bounces come in DSN MIME format, but don't include
any -Recipient: headers. Gotta just parse the text :(
NMS 4.1 (dfw-smtpin1.email.verio.net) seems even worse, but we'll try to
decipher the format here too.
"""
import re
from cStringIO import StringIO
pcre = re.compile(
r'This Message was undeliverable due to the following reason:',
re.IGNORECASE)
acre = re.compile(
r'(?P<reply>please reply to)?.*<(?P<addr>[^>]*)>',
re.IGNORECASE)
def flatten(msg, leaves):
if msg.is_multipart():
for part in msg.get_payload():
flatten(part, leaves)
else:
leaves.append(msg)
def process(msg):
if not msg.is_multipart():
return None
plainmsg = None
leaves = []
flatten(msg, leaves)
for i, subpart in zip(range(len(leaves)-1), leaves):
if subpart.get_type() == 'text/plain':
plainmsg = subpart
break
if not plainmsg:
return None
body = StringIO(plainmsg.get_payload())
addrs = []
while 1:
line = body.readline()
if not line:
break
mo = pcre.search(line)
if mo:
while 1:
line = body.readline()
if not line:
break
mo = acre.search(line)
if mo and not mo.group('reply'):
addrs.append(mo.group('addr'))
return addrs