首页 > 文章列表 > 使用IMAP和PHP构建高级电子邮件功能

使用IMAP和PHP构建高级电子邮件功能

php IMAP 邮件功能
454 2023-09-01

您将要创建的内容

在本教程中,我将向您介绍一些实际示例,说明如何使用 PHP 和 IMAP 构建用于管理电子邮件的新功能,而大型电子邮件提供商尚未为我们构建这些功能。

我对此产生兴趣始于 2010 年,当时我写了《(再次)彻底改变电子邮件的十二个 Gmail 创意》,但大多数我想要的创意仍然遥不可及。尽管电子邮件很重要,但电子邮件作为应用程序的创新却相当缓慢。

我们正被电子邮件淹没,管理收件箱仍然是一个沉重的负担。邮件服务和客户在这方面几乎没有采取任何措施来帮助我们。我们收到的大部分电子邮件都是由机器而不是人发送的,但我们却必须单独处理所有这些电子邮件。

对我自己的电子邮件的分析显示,我收到了来自 230 多个自动发件人的电子邮件,而实际发件人的数量要少得多。我厌倦了在 Gmail 中构建过滤器并填写无数的取消订阅表格。我希望更好地控制我的电子邮件管理并简化我的生活。

最后,在过去的一年里,我决定构建我需要的功能。结果是 Simplify Email (SE),这是一个您可以自己托管的小型网络应用程序,它提供了各种很酷的新电子邮件功能,您可以在项目网站上查看所有这些功能。

SE 最酷的一点是它是一个用于阅读、分析、路由和管理电子邮件的平台 - 可能性比比皆是。简化电子邮件本质上是一个“黑客”您自己的电子邮件的可编程游乐场。

我将引导您完成 SE 中使用 PHP、IMAP 和 MySQL 处理电子邮件的三个示例的代码:

  1. 检查收件箱并过滤邮件
  2. 对未知发件人实施白名单质询
  3. 报告未回复的电子邮件

本教程肯定会让您在使用 PHP 编写 IMAP 代码方面取得先机。但您也可以直接使用 Simplify Email 代码库。您可以以低至 10 美元的价格购买代码,并且有一个较旧的开源版本(缺少我们在下面描述的一些功能)。提供了典型 Linux 配置的安装指南。我还在 Digital Ocean 提供预装图像,价格为 25 美元,并提供手持代客安装服务。 SE 是在 Yii 框架中用 PHP 编写的。

请注意,除非您为 PHP 编译安全的 IMAP 库,否则您将无法通过本地开发计算机访问大多数电子邮件服务器。这是我鼓励人们在 Digital Ocean 中以 Droplet 方式运行 Simplify Email 的原因之一。还有一些技巧可以确保 Google 帐户安全,让您通过 IMAP 进入。

使用 IMAP

如何简化电子邮件的工作原理

借助 SE,您可以继续在网络和移动设备上使用您选择的电子邮件客户端。您无需更改任何应用程序或个人习惯。 SE 通过 IMAP 在幕后访问您的电子邮件帐户;作为智能个人助理,SE 会预处理您的电子邮件,根据您告诉它的所有内容将消息移动到适当的位置。

当来自熟悉的发件人的邮件到达时,SE 会将其移至您指定的文件夹。当未知发件人第一次收到邮件时,会将其移至审阅文件夹。

每隔几个小时(或按照您选择的频率),SE 就会向您发送一份摘要,说明其将邮件移至何处以及哪些邮件正在审核中。请注意,审核文件夹中包含培训发送者的链接,使得随着时间的推移培训 SE 变得非常容易。

使用IMAP和PHP构建高级电子邮件功能

您可以随时浏览您的审阅文件夹 - 无需等待摘要到达。但SE的优点是你不再需要浏览你的文件夹;您只需阅读摘要即可查看已收到的电子邮件并培训新发件人。

1。检查收件箱并过滤消息

SE 使用多个 cron 任务在服务器后台运行。每个都是从 DaemonController.php 调用的。

第一个,processInbox,被频繁调用,需要快速操作——它的工作是筛选电子邮件并尽快将其从收件箱移出并放入分类文件夹,称为过滤文件夹。

第二个,processFiltering,处理更加密集,对电子邮件执行更深入的操作,最终将邮件移动到最终目的地。

ProcessInbox 方法

cron 任务定期调用 processInbox

public function actionInbox() {
    
    // moves inbox messages to @filtering
    // runs frequently 
    $r = new Remote();
    $r->processInbox();	  
    
}

使用IMAP和PHP构建高级电子邮件功能

对于每个帐户,我们都会解密您的电子邮件凭据,然后使用 imap_open 创建指向您的收件箱文件夹的 IMAP 流:

public function open($account_id, $mailbox='',$options=NULL) {
  // opens folder in an IMAP account
  $account = Account::model()->findByPk($account_id);
  $this->hostname = $account->address;
  if (!stristr($this->hostname,'{'))
    $this->hostname = '{'.$this->hostname.'}';
  $cred = Account::model()->getCredentials($account->cred);
  if ($account->provider == Account::PROVIDER_ICLOUD) {
    // icloud accepts only name part of mailbox e.g. stevejobs vs. stevejobs@icloud.com
    $temp = explode('@',$cred[0]);
    $cred[0]=$temp[0];
  }
  $this->stream = imap_open($this->hostname.$mailbox,$cred[0],$cred[1],$options,1) or die('Cannot connect to mail server - account_id:'.$account_id .' '.print_r(imap_errors()));
}

processInbox 中,我们使用 PHP 库函数 imap_search 和 imap_fetch_overview 来检索消息数组:

// lookup folder_id of this account's INBOX
$folder_id = Folder::model()->lookup($account_id,$this->path_inbox);
$this->open($account_id,$this->path_inbox);
$cnt=0;
$message_limit= 50; // break after n messages to prevent timeout
echo 'Sort since: '.date("j F Y",$tstamp);           
// imap_search date format 30 November 2013
 $recent_messages = @imap_search($this->stream, 'SINCE "'.date("j F Y",$tstamp).'"',SE_UID); 
 if ($recent_messages===false) continue; // to do - continue into next account
 $result = imap_fetch_overview($this->stream, implode(',',array_slice($recent_messages,0,$message_limit)),FT_UID);

然后我们处理收件箱中的消息数组:

foreach ($result as $item) {         
   if (!$this->checkExecutionTime($time_start)) break;
   // get msg header and stream uid
   $msg = $this->parseHeader($item); 

这是公开可用的 IMAP 标头解析代码的改编版本,它收集 SE 完成各种任务所需的附加信息。基本上,它使用 imap_rfc822_parse_adrlist 来确定收件人信息、邮件 ID、主题和时间戳(或扫描已发送文件夹时的发件人信息):

  public function parseHeader($header) {
    // parses header object returned from imap_fetch_overview    
    if (!isset($header->from)) {
      return false;
    } else {
      $from_arr = imap_rfc822_parse_adrlist($header->from,'gmail.com');
      $fi = $from_arr[0];
      $msg = array(
        "uid" => (isset($header->uid))
              ? $header->uid : 0,
         "personal" => (isset($fi->personal))
            ? @imap_utf8($fi->personal) : "",
          "email" => (isset($fi->mailbox) && isset($fi->host))
              ? $fi->mailbox . "@" . $fi->host : "",
          "mailbox" => (isset($fi->mailbox))
            ? $fi->mailbox : "",
          "host" => (isset($fi->host))
            ? $fi->host : "",
          "subject" => (isset($header->subject))
              ? @imap_utf8($header->subject) : "",
          "message_id" => (isset($header->message_id))
                ? $header->message_id : "",
          "in_reply_to" => (isset($header->in_reply_to))
                    ? $header->in_reply_to : "",
          "udate" => (isset($header->udate))
              ? $header->udate : 0,
          "date_str" => (isset($header->date))
              ? $header->date : ""
      );    
      // handles fetch with uid and rfc header parsing
      if ($msg['udate']==0 && isset($header->date)) {
          $msg['udate']=strtotime($header->date);
      }
      $msg['rx_email']='';        
      $msg['rx_personal']='';
        $msg['rx_mailbox']='';
        $msg['rx_host']='';
      if (isset($header->to)) {        
        $to_arr = imap_rfc822_parse_adrlist($header->to,'gmail.com');
        $to_info = $to_arr[0];
        if (isset($to_info->mailbox) && isset($to_info->host)) {
          $msg['rx_email']=$to_info->mailbox.'@'.$to_info->host;
        }
        if (isset($to_info->personal))
          $msg['rx_personal']=$to_info->personal;
        if (isset($to_info->mailbox))
          $msg['rx_mailbox']=$to_info->mailbox;
        if (isset($to_info->host))
          $msg['rx_host']=$to_info->host;
      }
      return $msg;
    }
  }

我们在数据库中为发件人和邮件信封创建记录:

   // skip any system messages
   if ($msg['email']==$system_email) continue;
    // if udate is too old, skip msg
    if (time()-$msg['udate']>$this->scan_seconds) continue; // skip msg
    // default action
     $action = self::ACTION_MOVE_FILTERED;
     $isNew = $s->isNew($account_id,$msg["email"]);
    // look up sender, if new, create them
    $sender_id = $s->add($user_id,$account_id,$msg["personal"], $msg["mailbox"], $msg["host"],0);                       
    $sender = Sender::model()->findByPk($sender_id);
     // create a message in db if needed
     $message_id = $m->add($user_id,$account_id,0,$sender_id,$msg['message_id'],$msg['subject'],$msg['udate'],$msg['in_reply_to']);        
        $message = Message::model()->findByPk($message_id);

如果发件人对我们来说是新的(未知),我们将发送一封白名单质询电子邮件(我们将在下面的下一部分中详细讨论白名单质询):

if ($isNew) {
        $this->challengeSender($user_id,$account_id,$sender,$message);
      }

接下来,我们确定用户是否可能已将邮件从另一个文件夹拖回收件箱 - 打算通过拖放来训练它。如果是这样,我们会将此发件人的培训设置到收件箱。换句话说,下次我们只想将邮件从该发件人路由到收件箱:

         if ($message['status'] == Message::STATUS_FILTERED ||
   	    $message['status'] == Message::STATUS_REVIEW ||
   	    ($message['status'] == Message::STATUS_TRAINED && $message['folder_id'] <> $folder_id) ||
   	    ($message['status'] == Message::STATUS_ROUTED && $message['folder_id'] <> $folder_id))
   	    {
     	  // then it's a training
   	    $action = self::ACTION_TRAIN_INBOX;     	    
   	  } else if (($message['status'] == Message::STATUS_TRAINED || $message['status'] == Message::STATUS_ROUTED) && $message['folder_id'] == $folder_id) {
   	    // if trained already or routed to inbox already, skip it
   	    $action = self::ACTION_SKIP;  
   	    echo 'Trained previously, skip ';lb();   	  
   	    continue;  
   	  }

如果没有,我们将准备将邮件移至“过滤”文件夹以进行进一步处理。首先,如果通知的发件人匹配或关键字匹配(并且不是安静时间),我们可能会向用户的手机发送通知:

   if ($action == self::ACTION_MOVE_FILTERED) {
     $cnt+=1;         
     if ($sender->exclude_quiet_hours == Sender::EQH_YES or !$this->isQuietHours($user_id)) {
       // send smartphone notifications based on sender
       if ($sender->alert==Sender::ALERT_YES) {
         $this->notify($sender,$message,Monitor::NOTIFY_SENDER);
       }
       // send notifications based on keywords
       if (AlertKeyword::model()->scan($msg)) {
         $this->notify($sender,$message,Monitor::NOTIFY_KEYWORD);
       }               
     }               
     // move imap msg to +Filtering
     echo 'Moving to +Filtering';lb();
     //$result = @imap_mail_move($this->stream,$msg['uid'],$this->path_filtering,CP_UID);
     $result = $this->messageMoveHandler($msg['uid'],$this->path_filtering,false);             
     if ($result) {
       echo 'moved<br />';
       $m->setStatus($message_id,Message::STATUS_FILTERED);
     }
   } 

如果消息被拖到收件箱,那么我们将更新我们的训练设置:

else if ($action == self::ACTION_TRAIN_INBOX) {
     // set sender folder_id to inbox
     echo 'Train to Inbox';lb();
     $m->setStatus($message_id,Message::STATUS_TRAINED);
     // only train sender when message is newer than last setting
     if ($msg['udate']>=$sender['last_trained']) {
       $s->setFolder($sender_id,$folder_id);
     } 
   }

ProcessFiltering方法

二次处理方法称为processFiltering,也在DaemonController.php中。它完成了将邮件移动到适当文件夹的更耗时的工作:

public function actionIndex()
{
  // processes messages in @Filtering to appropriate folders
  $r = new Remote();
  $r->processFiltering();
  // Record timestamp of cronjob for monitoring
  $file = file_put_contents('./protected/runtime/cronstamp.txt',time(),FILE_USE_INCLUDE_PATH);	  
}

此方法会打开您的电子邮件帐户来搜索最近的邮件并收集有关它们的数据。它还使用 imap_searchimap_fetch_overviewparseHeader:

$tstamp = time()-(7*24*60*60); // 7 days ago
$recent_messages = @imap_search($this->stream, 'SINCE "'.date("j F Y",$tstamp).'"',SE_UID);
if ($recent_messages===false) continue; // to do - continue into next account
$result = imap_fetch_overview($this->stream, implode(',',array_slice($recent_messages,0,$message_limit)),FT_UID);
foreach ($result as $item) {         
      $cnt+=1;
      if (!$this->checkExecutionTime($time_start)) break;
      // get msg header and stream uid
      $msg = $this->parseHeader($item);            

过滤文件夹中每条消息的主要处理循环非常详细。首先我们查看收件人地址,因为 SE 允许人们通过收件人地址来训练文件夹,例如发送至 happyvegetarian.com 域的邮件将转到 veggie 文件夹:

 // Set the default action to move to the review folder
 $action = self::ACTION_MOVE_REVIEW;
 $destination_folder =0;
 // look up & create recipient
 $recipient_id = $r->add($user_id,$account_id,$msg['rx_email'],0);
 $routeByRx = $this->routeByRecipient($recipient_id);
 if ($routeByRx!==false) {
  $action = $routeByRx->action;
  $destination_folder = $routeByRx->destination_folder;
 }            

然后我们查找发件人并在数据库中创建一条新记录(如有必要)。如果发送者存在训练,我们可以设置目标文件夹:

 // look up sender, if new, create them
 $sender_id = $s->add($user_id,$account_id,$msg["personal"], $msg["mailbox"], $msg["host"],0);                       
 $sender = Sender::model()->findByPk($sender_id);
 // if sender destination known, route to folder
 if ($destination_folder ==0 && $sender['folder_id'] > 0) {
   $action = self::ACTION_ROUTE_FOLDER;  
   $destination_folder = $sender['folder_id'];      
 }
 

如果未经训练的(新)发件人已通过白名单质询(我们将在下面的下一节中讨论)验证自己,那么我们会将此邮件路由到收件箱:

// whitelist verified senders go to inbox
 if ($sender->is_verified==1 && $sender['folder_id'] ==0 && UserSetting::model()->useWhitelisting($user_id)) {
   // place message in inbox
   $action = self::ACTION_ROUTE_FOLDER;  
   $destination_folder = Folder::model()->lookup($account_id,$this->path_inbox);             
 }

然后,我们在数据库中创建一个消息条目,其中包含有关此消息的信封信息:

  // create a message in db
      $message = Message::model()->findByAttributes(array('message_id'=>$msg['message_id']));
  if (!empty($message)) {
    // message exists already, 
	  $message_id = $message->id;    	  
  } else {
    $message_id = $m->add($user_id,$account_id,0,$sender_id,$msg['message_id'],$msg['subject'],$msg['udate'],$msg['in_reply_to']);         
  }

如果邮件来自未知、未经验证的发件人,我们可以将邮件移至审阅文件夹。审阅文件夹包含来自我们无法识别的发件人的所有邮件。

如果邮件来自已知发件人,并且我们已确定目的地,只要不是安静时间(且请勿打扰已关闭),我们就可以将其移动:

  if ($recipient_id!==false) $m->setRecipient($message_id,$recipient_id);
  if ($action == self::ACTION_MOVE_REVIEW) {
    echo 'Moving to +Filtering/Review';lb();
    //$result = @imap_mail_move($this->stream,$msg['uid'],$this->path_review,CP_UID);
    $result = $this->messageMoveHandler($msg['uid'],$this->path_review,false);               
    if ($result) {
      echo 'moved<br />';
      $m->setStatus($message_id,Message::STATUS_REVIEW);
    }      
 } else if ($action == self::ACTION_ROUTE_FOLDER || $action == self::ACTION_ROUTE_FOLDER_BY_RX) {
  // lookup folder name by folder_id
  $folder = Folder::model()->findByPk($destination_folder);       
  // if inbox & quiet hours, don't route right now
  if (strtolower($folder['name'])=='inbox' and $sender->exclude_quiet_hours == Sender::EQH_NO and $this->isQuietHours($user_id)) continue;
  echo 'Moving to '.$folder['name'];lb();
  $mark_read = Folder::model()->isMarkRead($folder['mark_read']) || Sender::model()->isMarkRead($sender['mark_read']);
  //$result = @imap_mail_move($this->stream,$msg['uid'],$folder['name'],CP_UID);
  $result = $this->messageMoveHandler($msg['uid'],$folder['name'],$mark_read);
  if ($result) {
    echo 'moved<br />';
    $m->setStatus($message_id,Message::STATUS_ROUTED);         
    $m->setFolder($message_id,$destination_folder);
  }
}

在安静时间,邮件主要保存在过滤文件夹中。

每隔几个小时,就会有一个不同的进程使用消息表记录构建消息摘要,以确定最近收到和过滤的电子邮件以及它们的路由方式。

2。对未知发件人实施白名单质询

白名单挑战的目标是保留来自未知发件人的任何消息,例如可能是您收件箱中的营销机器人或垃圾邮件发送者。 SE 将来自未知发件人的邮件放入审阅文件夹中。但是,如果您打开白名单,我们会发送一封质询电子邮件,让发件人有机会验证自己是否是人类。如果他们回复,我们会将邮件移至您的收件箱。如果结果表明该电子邮件是不需要的,您可以从摘要中删除该邮件或将其拖到您想要将其训练到的任何文件夹中。

用户可以在设置中打开和关闭白名单:

使用IMAP和PHP构建高级电子邮件功能

为了实施白名单,每当新发件人收到邮件时,我们都会发送电子邮件质询:

if ($isNew) {
        $this->challengeSender($user_id,$account_id,$sender,$message);
      }

ChallengeSender 向用户发送一个编码链接供他们单击。我们还采取了一些保护措施,以确保我们不会陷入带有外出消息的电子邮件循环中:

 public function challengeSender($user_id,$account_id,$sender,$message) {
   // whitelist email challenge
   $yg = new Yiigun();
   $ac = Account::model()->findByPk($account_id);
   if (!empty($ac['challenge_name']))
     $from = $ac['challenge_name'].' <no-reply@'.$yg->mg_domain.'>';
    else
      $from = 'Filter <no-reply@'.$yg->mg_domain.'>';      
   $cred = Account::model()->getCredentials($ac->cred);
   $account_email = $cred[0];
   unset($cred); 
   // safety: checks no recent email
   if ($sender->last_emailed>(time()-(48*60*60))) return false;   
   if ($sender->isBot($sender['email'])) {
     // to do - can also set this person to bulk by default
     return false;
   }
$link=Yii::app()->getBaseUrl(true)."/sender/verify/s/".$sender->id."/m/".$message->id.'/u/'.$message->udate;
    $subject = 'Please verify the message you sent to '.$account_email;
    $body="<p>Hi,<br /><br /> I'm trying to reduce unsolicited email. Could you please verify your email address by clicking the link below:<br /><a href="".$link.'">'.$link.'</a><br /><br />Verifying your email address will help speed your message into my inbox. Thanks for your assistance!</p>';
    $yg->send_html_message($from, $sender['email'], $subject,$body);
    // update last_emailed
    $sender->touchLastEmailed($sender->id);
 }

然后,如果收件人单击编码链接,我们会在数据库中验证它们。发送者控制器处理这些请求并检查它们的有效性:

  public function actionVerify($s = 0, $m=0,$u=0) {
    // verify that secure msg url from digest is valid, log in user, show msg
    $sender_id = $s;
    $message_id = $m;
    $udate = $u;
    $msg = Message::model()->findByPk($message_id);
    if (!empty($msg) && $msg->sender_id == $sender_id && $msg->udate == $udate) {
      $result = 'Thank you for your assistance. I'll respond to your email as soon as possible.';
      $a = new Advanced();
      $a->verifySender($msg->account_id,$sender_id);
    } else {
      $result = 'Sorry, we could not verify your email address.';
    }
    	$this->render('verify',array(
			'result'=>$result,
		));
  }

这告诉我们的处理循环将此消息和将来的消息从该发件人移动到收件箱。

3。报告未回复的电子邮件

有时,查看您已发送但未收到回复的消息摘要会有所帮助。为了识别这些邮件,Simplify Email 会监视已发送但尚未收到回复的邮件。

我们收到的每条消息都包含一个唯一的 ID,称为 message_id(IMAP 规范的一部分)。它通常看起来像这样:

Message-Id: <CALe0OAaF3fb3d=gCq2Fs=Ex61Qp6FdbiA4Mvs6kTQ@mail.gmail.com>

此外,当发送消息以回复其他消息时,它们有一个 in_reply_to 字段,该字段链接回原始 message_id

因此,我们使用 SQL 查询来查找所有收到的消息,这些消息没有引用其 message_id 的相应回复消息。为此,我们在没有 in_reply_to id 的情况下使用 LEFT OUTER JOIN:

public function getUnanswered($account_id,$mode=0, $range_days = 7) {
    if ($mode==0)
      $subject_compare = 'not';
    else
      $subject_compare = '';
    $query = Yii::app()->db->createCommand("SELECT fi_sent_message.id, fi_sent_message.recipient_id as sender_id,fi_sent_message.subject,fi_sent_message.udate,fi_message.in_reply_to,fi_sent_message.message_id  FROM fi_sent_message LEFT OUTER JOIN fi_message ON fi_message.in_reply_to = fi_sent_message.message_id WHERE fi_sent_message.account_id = ".$account_id." AND fi_message.in_reply_to is null and fi_sent_message.udate > ".(time()-(3600*24*$range_days))." and fi_sent_message.subject ".$subject_compare." like 'Re: %' ORDER BY fi_sent_message.udate  DESC")->queryAll();
    return $query;
  }

我们使用 $subject_compare 模式来区分我们发送的尚未回复的消息和我们发送给尚未回复的线程的回复。以下是您帐户中的未回复消息报告:

使用IMAP和PHP构建高级电子邮件功能

SE 还将此信息作为可选摘要提供,称为未回复电子邮件摘要。您可以每天、每隔几天或每周收到它。

我们还使用类似的 SQL 表格和 Google Charts 来提供有关某些人向您发送电子邮件的频率的报告:

使用IMAP和PHP构建高级电子邮件功能

  public function reportInbound($account_id,$range=30,$limit = 100) {
    $result= Yii::app()->db->createCommand('SELECT fi_sender.personal, fi_sender.email,count(sender_id) as cnt
      FROM fi_message LEFT JOIN fi_sender ON fi_sender.id =fi_message.sender_id WHERE fi_sender.account_id = :account_id AND fi_message.created_at > DATE_SUB( NOW() , INTERVAL :range DAY )  
      GROUP BY sender_id ORDER BY cnt desc LIMIT :limit ')->bindValue('range',$range)->bindValue('account_id',$account_id)->bindValue('limit',$limit)->queryAll();
    return $result;
  }

我很快就会撰写更多有关 Tuts+ 的 Google Charts 的文章。

后续步骤

我希望您已经发现 Simplify Email 足够有趣,可以尝试 PHP IMAP 编程。您可以构建许多很酷的功能,而不需要大型电子邮件提供商做任何新的事情。

如果您有任何疑问或更正,请在评论中提出。如果您想继续关注我未来的 Tuts+ 教程和其他系列,请关注 @reifman 或访问我的作者页面。您也可以在这里联系我。

相关链接

以下是一些您可能会觉得有用的附加链接:

  • 简化电子邮件
  • 简化电子邮件简介(视频)
  • (再次)彻底改变电子邮件的 12 个 Gmail 创意

  • BoingBoing 中简化电子邮件的报道(此处和此处)
  • PHP IMAP 参考
  • Yii 框架简介 (Tuts+)