Email Parse and Python Cookbook
David McInnis
david at dataovation.com
Thu Nov 7 17:54:29 EST 2002
I am trying to create a script that will read and parse all of my
support email messages. The ultimate goal is to inject these messages
into our support queue and save the attached files to disk. I am using
Qmail / vpopmail which is great because each message is stored as a file
and each account has its own directory structure. Therefore I do not
need to connect to a pop3 account and can save on the network overhead.
My problem is this. I am using a sample out of the Python Cookbook but
this example fails on some messages. Works on most.
David McInnis
# ********* HERE IS MY SCRIPT
#!/usr/local/bin/python2.2
import sys
import os
import email.Parser
import types
def main():
dir = "/usr/scripts/dev/files/"
maildir = "/home/vpopmail/domains/mydomain.com/support/Maildir/cur"
for file in os.listdir(maildir):
print os.path.join(maildir, file)
fp = open(os.path.join(maildir, file), "rb")
p = email.Parser.Parser()
msg = p.parse(fp)
fp.close()
#print msg.get("From")
#print msg.get("Content-Type")
counter = 1
for part in msg.walk():
if part.get_main_type() == 'multipart':
continue
filename = part.get_param("name")
if filename==None:
filename = "part-%i" % counter
counter += 1
fp = open(os.path.join(dir, filename), 'wb')
print os.path.join(dir, filename)
fp.write(part.get_payload(decode=1))
fp.close()
if __name__ == '__main__':
main()
# ********* HERE IS THE RESULT OF EXECUTING THE SCRIPT
]#./inject.py
/home/vpopmail/domains/mydomain.com/support/Maildir/cur/1036001583.5676.
wf.mydomain.com,S=119691:2,
/usr/scripts/dev/files/part-1
/usr/scripts/dev/files/part-2
/usr/scripts/dev/files/SaucierPresentation_Resume.p4495.f36064.doc
/usr/scripts/dev/files/SaucierPresentation_Cover_Ltr.p4495.f36065.doc
/home/vpopmail/domains/
mydomain.com/support/Maildir/cur/1036006414.8616.wf.mydomain.com,S=14076
8:2,
Traceback (most recent call last):
File "./inject.py", line 49, in ?
main()
File "./inject.py", line 24, in main
msg = p.parse(fp)
File "/usr/local/lib/python2.2/email/Parser.py", line 41, in parse
self._parsebody(root, fp)
File "/usr/local/lib/python2.2/email/Parser.py", line 134, in
_parsebody
msgobj = self.parsestr(part)
File "/usr/local/lib/python2.2/email/Parser.py", line 45, in parsestr
return self.parse(StringIO(text))
File "/usr/local/lib/python2.2/email/Parser.py", line 40, in parse
self._parseheaders(root, fp)
File "/usr/local/lib/python2.2/email/Parser.py", line 81, in
_parseheaders
raise Errors.HeaderParseError(
email.Errors.HeaderParseError: Not a header, not a continuation
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20021107/26186bf3/attachment.html>
More information about the Python-list
mailing list