简体   繁体   English

Python:Postfix stdin

[英]Python : Postfix stdin

I want to make postfix send all emails to a python script that will scan the emails. 我想让postfix将所有电子邮件发送到将扫描电子邮件的python脚本。

However, how do I pipe the output from postfix to python ? 但是,如何将postfix的输出传递给python?

What is the stdin for Python ? Python的stdin是什么?

Can you give a code example ? 你能给出一个代码示例吗?

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. 而不是调用sys.stdin.readlines()然后循环并将行传递email.FeedParser.FeedParser().feed()迈克尔建议的email.FeedParser.FeedParser().feed() ,您应该将文件对象直接传递给电子邮件解析器。

The standard library provides a conveinience function, email.message_from_file(fp) , for this purpose. 为此,标准库提供了一个会话功能,即email.message_from_file(fp) Thus your code becomes much simpler: 因此,您的代码变得更加简单:

import email
msg = email.message_from_file(sys.stdin)

To push mail from postfix to a python script, add a line like this to your postfix alias file: 要将邮件从postfix推送到python脚本,请将这样的行添加到postfix别名文件中:

# 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: python email.FeedParser模块可以通过执行以下操作来构造一个表示来自stdin的MIME电子邮件消息的对象:

# 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. 从这里开始,您需要迭代msg的MIME部分并相应地对它们进行操作。 Refer to the documentation on email.Message objects for the methods you'll need. 有关您需要的方法,请参阅email.Message对象的文档 For example email.Message.get("Header") returns the header value of Header . 例如email.Message.get("Header")返回的报头值Header

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM