Bounce Email handling with PHP?

后端 未结 14 1527
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 04:30

Here is my scenario:

I have 2 email accounts: admin@domain.com and bounce@domain.com.

I want to send email to all my users with admin@domain.com but then \"r

14条回答
  •  盖世英雄少女心
    2020-11-28 05:25

    You can use imap_open to access your mails from PHP.

    This functions also works for POP3 but not every function may work here. However I guess in 2018 most email-clients should support IMAP.

    This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are only available on IMAP servers.

    Here is a little example, how to iterate through your emails:

      /* connect to server */
      $hostname = "{$your-server:$your-port}INBOX";
      $username = 'my-username';
      $password = '123';
    
      /* try to connect */
      $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to mailbox: ' . imap_last_error());
    
      /* grab emails */
      $emails = imap_search($inbox,'ALL');
    
      /* if emails are returned, cycle through each... */
      if($emails) {
        /* for every email... */
        foreach($emails as $email_number) {
    
            $message = imap_body($inbox,$email_number,2);
            $head    = imap_headerinfo($inbox, $email_number,2);
            // Here you can handle your emails
            // ...
            //  ...
          }
      }
    

    In my case, I know that I always get my mail delivery failed from Mailer-Daemon@myserver.com. So I could identify bounces like that:

    if($head->from[0]->mailbox == 'Mailer-Daemon')
    {
      // We have a bounce mail here!
    }
    

    You said:

    When, the email can't be sent, it's sent to bounce@domain.com, the error message could be 553 (non existent email ...) etc.

    So if your bounce emails have the subject "Mail delivery failed: Error 553" then you could identify them by the subject like this:

    if($head->subject == 'Mail delivery failed: Error 553')
    {
      // We have a bounce mail here!
    }
    

    The failed email address is not in the header, so you need to parse it from the $message variable with some smart code.

提交回复
热议问题