7

I want to make postfix send all emails to a python script that will scan the emails.

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

What is the stdin for Python ?

Can you give a code example ?

Lucas Kauffman
  • 6,226
  • 13
  • 57
  • 81

2 Answers2

12

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:

import email
msg = email.message_from_file(sys.stdin)
lfaraone
  • 44,680
  • 16
  • 48
  • 70
6

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.

Marcob
  • 48
  • 4
Michael Berkowski
  • 253,311
  • 39
  • 421
  • 371