添加自己的postfix邮件过滤器

添加自己的postfix邮件过滤器


我们需要修改/etc/postfix/master.cf:

1. 添加:

filter    unix  -       n       n       -       10      pipe
    flags=Rq user=filter null_sender=
    argv=/tmp/myfilter.sh -f ${sender} -- ${recipient}

 

2. 在smtp下面添加绿色的部分
smtp      inet n      -        -       -        -       smtpd
        -o content_filter=filter:dummy

然后让postfix加载配置:

$ sudo service postfix reload

我们的脚本可以如下:

—————–myfilter.sh————————–

1 #!/bin/sh
  2
  3 # Simple shell-based filter. It is meant to be invoked as follows:
  4 #       /path/to/script -f sender recipients…
  5
  6 # Localize these. The -G option does nothing before Postfix 2.3.
  7 INSPECT_DIR=/tmp
  8 SENDMAIL="/usr/sbin/sendmail -G -i" # NEVER NEVER NEVER use "-t" here.
  9
 10 # Exit codes from <sysexits.h>
 11 EX_TEMPFAIL=75
 12 EX_UNAVAILABLE=69
 13
 14 # Clean up when done or when aborting.
 15 trap "rm -f in.$$" 0 1 2 3 15
 16
 17 # Start processing.
 18 cd $INSPECT_DIR || {
 19     echo $INSPECT_DIR does not exist; exit $EX_TEMPFAIL; }
 20

 21 cat >in.$$ || {
 22     echo Cannot save mail to file; exit $EX_TEMPFAIL; }
 23
 24 # Specify your content filter here.
 25 /tmp/emailFilter.py <in.$$ || {
 26    echo Message content rejected; exit $EX_UNAVAILABLE; }
 27
 28 echo send mail now
 29 echo $@
 30 echo in.$$
 31 $SENDMAIL "$@" <in.$$
 32
 33 exit $?

 

—————–myfilter.py—————————-

  1 #! /usr/bin/python
  2
  3 import sys
  4 from email.parser import Parser
  5
  6 raw = ''
  7 f=open('/tmp/email.log', 'a+')
  8 f.write('———————————————–\n')
  9 for line in sys.stdin:
 10     raw = raw + line
 11     f.write( line )
 12
 13 parser = Parser()
 14 email = parser.parsestr( raw )
 15 f.write('############################\n')
 16 f.write( 'From:' + email.get('From' ) + '\n' )
 17 f.write( 'To:' + email.get('To' ) + '\n' )
 18 f.write( 'Subject:' + email.get('Subject' ) + '\n' )
 19 f.write('############################\n')
 20 f.write('———————————————–\n')
 21 f.close()

  22 exit( 0 )

 

成功的话,会在 /tmp下面生成一个 mail.log的文件,并且把邮件的信息写下来,分析其中的from, to和主题。

注意 22行中这里是exit(0),如果是返回 69,

exit(69)

那么这个邮件就不会被转发到用户的邮箱,而是直接丢弃,官网原话:

“If the content filter program finds a problem, the mail is bounced by terminating with exit status 69 (EX_UNAVAILABLE). Postfix will send the message back to the sender as undeliverable mail. “

 

可以参考:

http://blog.thecodingmachine.com/content/triggering-php-script-when-your-postfix-server-receives-mail

更多官方信息请参看:

http://www.postfix.org/FILTER_README.html

版权所有,禁止转载. 如需转载,请先征得博主的同意,并且表明文章出处,否则按侵权处理.

    分享到:
This entry was posted in Linux系统学习. Bookmark the permalink.

One Response to 添加自己的postfix邮件过滤器

  1. jkl says:

    没用啊,maste.cf 中配置的-o content_filter=filter:dummy根本不起作用,就跟没配一样

Leave a Reply

Your email address will not be published. Required fields are marked *

*