📜 ⬆️ ⬇️

PHP incoming mail processing

I want to share a recipe on how to combine a php-script and Postfix mail server for automatic processing of incoming mail.

With this bundle, we collect statistics on the number of returns of bounce letters: Undelivered Mail Returned to Sender.

On other sites, I have seen similar functionality, for example, to publish content by sending it to a mailbox assigned to the user.
')

How to do it

  1. First, make sure you have a working mail server.

    You can make a separate mailer in the subdomain, just make 2 entries in the DNS:
     rob.mydomain.ru. A ip-- rob.mydomain.ru. MX rob.mydomain.ru. 

  2. Edit the file with aliases / etc / aliases:
    add the line there:
    robot: "|php -q ///.php"
    robot is the name of the mailbox;
    ///.php - script processing incoming.

    after editing, run the newaliases command

  3. In the postfix main.cf settings, I recommend adding a parameter:
    recipient_delimiter = +

    then it will be possible to encode additional information in the address: robot+someId@rob.mydomain.ru

    All letters to such addresses will also process our script.
    someId can be a user id or any other data.
  4. create a script-processor of letters:
     <?php /** *       * *   smtp-  RECIPIENT, SENDER   postfix *    $_ENV;   : * http://www.postfix.org/local.8.html  EXTERNAL COMMAND DELIVERY */ //    STDIN $msg = file_get_contents("php://stdin"); //  $sender = getenv('SENDER'); //  $recipient = getenv('RECIPIENT'); //  list($header, $body) = explode("\n\n", $msg, 2); //   Subject:  From: $subject = ''; $from = ''; $headerArr = explode("\n", $header); foreach ($headerArr as $str) { if (strpos($str, 'Subject:') === 0) { $subject = $str; } if (strpos($str, 'From:') === 0) { $from = $str; } } //      : $logMsg = "=== MSG ===\n"; $logMsg .= "SENDER: $sender\n"; $logMsg .= "RECIPIENT: $recipient\n"; $logMsg .= "$from\n"; $logMsg .= "$subject\n\n"; $logMsg .= "$msg\n"; file_put_contents('/tmp/inb.log',$logMsg, FILE_APPEND); 
  5. send an email to robot@rob.mydomain.ru and look in the log /tmp/inb.log

Done!

Source: https://habr.com/ru/post/126448/


All Articles