您可以在收到的邮件上指定内容过滤器 - 这样做您需要通过以下方式修改您的 master.cf 文件:
...
submission inet n - n - - smtpd
...
-o content_filter=yourfilter:
...
yourfilter unix - n n - - pipe
user=[user on which the script will be executed]
argv=php /path/to/your/script.php --sender='${sender}' --recipient='${recipient}'
接下来,您需要编写 script.php,以便正确使用已提供的参数(--sender=... 和--recipient=...)和邮件正文将由标准输入提供。
这是一个如何从标准输入获取电子邮件的示例(我使用这个,稍后使用 Zend\Mail\Message::fromString() 创建 Message 对象):
/**
* Retrieves raw message from standard input
* @throws \RuntimeException if calling controller was not executed on console
* @return string raw email message retrieved from standard input
*/
protected function retrieveMessageFromStdin() {
$request = $this->getRequest();
if (!$request instanceof ConsoleRequest)
throw new \RuntimeException('Action can be used only as console action !');
$stdin = fopen('php://stdin', 'r');
$mail_contents = "";
while (!feof($stdin)) {
$line = fread($stdin, 1024);
$mail_contents .= $line;
}
fclose($stdin);
$mail_contents = preg_replace('~\R~u', "\r\n", $mail_contents);
return $mail_contents;
}
根据参数 - 我使用 ZF2,因此您应该阅读如何在那里编写控制台应用程序或使用不同的技术,更符合您的框架。
非常重要的是,如果您希望在邮箱中接收邮件 - 您还需要将电子邮件“重新注入”回 postfix。我的做法如下:
/**
* Reinjects message to sendmail queue
*
* @param array $senders array of senders to be split into several sender addresses passed to sendmail (in most cases it is only 1 address)
* @param array $recipients array of recipients to be split into several recipient addresses passed to sendmail
* @param string $sendmaiLocation sendmailLocation string full path for sendmail (should be taken from config file)
* @return number return value for sendmail
*/
public function reinject(array $senders, array $recipients, string $sendmaiLocation) {
foreach ($senders as $addresses)
$senderAddress .= " " . $addresses;
foreach ($recipients as $addresses)
$recipientAddress .= " " . $addresses;
$sendmail = $sendmaiLocation . " -G -i -f '" . $senderAddress . "' -- '" . $recipientAddress . "'";
$handle = popen($sendmail, 'w');
fwrite($handle, $this->toString());
return pclose($handle);
}
基本上你可以使用上面的功能,根据你的需要自定义。然后您可以稍后使用我之前提到的命令行参数中的参数执行它。
希望这会有所帮助:)