Python : Postfix stdin

怎甘沉沦 提交于 2019-12-04 04:21:59
Michael Berkowski

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.

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