Python : Postfix Stdin
Solution 1:
Rather than calling sys.stdin.readlines()
then looping and passing the lines to email.FeedParser.FeedParser().feed()
as suggested by Michael, you should instead pass the file object directly to the email parser.
The standard library provides a conveinience function, email.message_from_file(fp)
, for this purpose. Thus your code becomes much simpler:
importemailmsg= email.message_from_file(sys.stdin)
Solution 2:
To push mail from postfix to a python script, add a line like this to your postfix alias file:
# send to emailname@example.com
emailname: "|/path/to/script.py"
The python email.FeedParser
module can construct an object representing a MIME email message from stdin, by doing something like this:
# Read from STDIN into array of lines.
email_input = sys.stdin.readlines()
# email.FeedParser.feed() expects to receive lines one at a time# msg holds the complete email Message object
parser = email.FeedParser.FeedParser()
msg = None
for msg_line in email_input:
parser.feed(msg_line)
msg = parser.close()
From here, you need to iterate over the MIME parts of msg
and act on them accordingly. Refer to the documentation on email.Message
objects for the methods you'll need. For example email.Message.get("Header")
returns the header value of Header
.
Post a Comment for "Python : Postfix Stdin"