Python : Postfix stdin

落爺英雄遲暮 提交于 2019-12-21 12:08:44

问题


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 ?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/8312001/python-postfix-stdin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!