【问题标题】:How to catch bounced emails in PHP?如何在 PHP 中捕获退回的电子邮件?
【发布时间】:2014-01-26 14:05:09
【问题描述】:

如果通过 PHP 函数 mail() 发送电子邮件时被退回,我想保存电子邮件吗?捕捉它的最佳方法是什么?

【问题讨论】:

标签: php email email-bounces


【解决方案1】:

首先,您需要使用带有附加标头的 mail() 函数发送电子邮件。您将返回电子邮件地址指向一个邮箱,您将在其中收集退回的电子邮件。下面的代码是一个如何实现的示例。

$recipient = "jack@someotherexample.com";
$subject = "test subject";
$message = "test message";

$body = "<html>\r\n";
$body .= "<body style=\"font-family:Verdana, Verdana, Geneva, sans-serif; font-size:12px; color:#666666;\">\r\n";
$body .= $message;
$body .= "</body>\r\n";
$body .= "</html>\r\n";

$headers  = "From: My site<noreply@example.com>\r\n";
$headers .= "Reply-To: bounce@example.com\r\n";
$headers .= "Return-Path: bounce@example.com\r\n";
$headers .= "X-Mailer: PHP\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$result = mail($recipient, $subject, $body, $headers); 

if($result)
{
    echo "email sent";
}
else
{
    echo "email send error";
}

SOURCE

您只需检查收件箱中是否有退回的错误电子邮件。下面的示例代码将连接到 imap 收件箱,获取并打印在那里找到的所有电子邮件。您可以根据自己的需要轻松定制它。

/* connect to server */
$hostname = '{example.com:143}INBOX';
$username = 'bounce@example.com';
$password = 'password';

/* 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) {

  /* begin output var */
  $output = '';

  /* put the newest emails on top */
  rsort($emails);

  /* for every email... */
  foreach($emails as $email_number) {

    /* get information specific to this email */
    $overview = imap_fetch_overview($inbox,$email_number,0);
    $message = imap_fetchbody($inbox,$email_number,1.2);

    /* output the email header information */
    $output.= '<div '.($overview[0]->seen ? 'read' : 'unread').'">';
    $output.= '<span>'.$overview[0]->subject.'</span> ';
    $output.= '<span>'.$overview[0]->from.'</span>';
    $output.= '<span>'.$overview[0]->date.'</span>';
    $output.= '</div>';

    /* output the email body */
    $output.= '<div class="body">'.$message.'</div>';
  }

  echo $output;
}

/* close the connection */
imap_close($inbox);

SOURCE

【讨论】:

【解决方案2】:

将退回电子邮件地址添加到电子邮件标题中,并通过 PHP 监控该电子邮件帐户的退回情况。

【讨论】:

  • 对不起,我没明白,你能用示例代码写一下吗,在此先感谢...
猜你喜欢
  • 2011-12-14
  • 2018-03-07
  • 2011-02-02
  • 2019-05-07
  • 2013-02-18
  • 1970-01-01
  • 2017-09-18
  • 2016-09-28
  • 2011-05-24
相关资源
最近更新 更多