Python: Postfix stdin

I want postfix to send all emails to a python script that will check emails.

However, how do I pass the output from the postfix to python?

What is stdin for Python?

Can you give some sample code?

+7
source share
2 answers

To send mail from a postfix to a python script, add a line like this to your postfix alias:

# send to emailname@example.com emailname: "|/path/to/script.py" 

python email.FeedParser module can build an object representing the stdin MIME email 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 msg part and act accordingly. See the documentation for email.Message objects for the methods you need. For example, email.Message.get("Header") returns the value of the Header .

+6
source

Instead of calling sys.stdin.readlines() , then sys.stdin.readlines() over and passing the strings to email.FeedParser.FeedParser().feed() , as suggested by Michael, you should pass the file object directly to the email parser.

The standard library provides the conveinience function, email.message_from_file(fp) , for this purpose. Thus, your code becomes much simpler:

 import email msg = email.message_from_file(sys.stdin) 
+9
source

All Articles