如何在PHP中捕获退回的电子邮件? [英] How to catch bounced emails in PHP?

查看:122
本文介绍了如何在PHP中捕获退回的电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to save emails if it is bounced while sending email through PHP function mail() ? What is best way to catch that ?

推荐答案

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

First you need to send email with mail() function with the use of additional headers. You point the return email address to a mailbox where you will gather the bounced emails. The below code is an example how to achieve that.

$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";
}

来源

比起您,您只需要检查收件箱中是否有退回的错误电子邮件.下面的示例代码将连接到imap收件箱,获取并打印出它在其中找到的所有电子邮件.您可以轻松地根据需要对其进行自定义.

Than you just check the inbox for bounced error emails. The below example code will connect to an imap inbox, fetch and print out all the emails it finds there. You can easily customise it to your needs.

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

来源

这篇关于如何在PHP中捕获退回的电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆