3

我已经成功编写了连接到我的邮件服务器并检索所有新邮件的标题和正文的脚本。我想进一步检测附件是否存在(仅图像),如果存在,下载到服务器。

如何使用 PHP 和 IMAP 来解决这个问题?

提前致谢

4

1 回答 1

1

KimNyholm 发布了一组 imap 客户端方法,其中包含您提出的目标: https ://github.com/KimNyholm/ubuntu-web-development/blob/master/php/imapClient.php

由于缺乏完整的教程和代码示例来处理 php imap 消息,他编写了此代码,正如他在这里解释的那样:http: //kimnyholm.com/a-simple-imap-mail-reader-client/并基于他的一些drupal 库中的代码。

我附上了执行您提到的步骤的方法的摘录,我希望它可以解决问题,即使我发现它不是最近的:

检查其中的附件和图像:

// ATTACHMENT
  // Any part with a filename is an attachment,
  // so an attached text file (type 0) is not mistaken as the message.
  if(isset($parameter['filename']) || isset($parameter['name'])) {
    $filename = ($parameter['filename'])? $parameter['filename'] : $parameter['name'];
    $filename=iconv_mime_decode($filename, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
    $id = isset($part->id) ? $part->id : '' ;
    $attachments[] = array('inline' => false, 'filename' => $filename, 'part' => $partNo, 'data' => $data, 'id' => $id);
  }
  if ($type==TYPEIMAGE){
    $info=fetchImageInfo($mailbox, $emailNumber, $partNo);
    $attachments[] = array('inline' => true, 'filename' => $info['filename'], 'part' => $partNo, 'data' => $data, 'id' => $info['id']);
  }

在这里,他将数据保存到 tempdir 并下载:

function EmailAttachmentsSave(&$mail){
  $html = '';
  $attachments=$mail->attachments;
  $msgNo=trim($mail->headerInfo->Msgno);
  foreach ($attachments as $attachment) {
    $partNo=$attachment['part'];
    $tmpDir= "imapClient/$msgNo/$partNo";
    $dirExists= is_dir($tmpDir);
    if (!$dirExists){
      $dirExists= mkdir($tmpDir, 0777, true) ;
    }
    $fileName=$attachment['filename'];
    $tmpName = "$tmpDir/$fileName";
    $saved = $dirExists && file_put_contents($tmpName, $attachment['data']);
    $tmpName=htmlentities($tmpName);
    $fileName=htmlentities($fileName);
    if (!$attachment['inline']){
      $html .= '<span><a href="' . $tmpName . '">' . $fileName . '</a> </span>';
    }
    $cid =$attachment['id'];
    if (isset($cid)){
      $mail->htmlText=EmailEmbeddedLinkReplace($mail->htmlText,$cid,$tmpName);
    }
  }
  return $html ;
}

function EmailPrint($mail){
  $headerInfo=$mail->headerInfo;
  $html = '<h4>' . htmlentities($headerInfo->subject) . '</h4>';
  $html .= '<p>From: ' . htmlentities($headerInfo->fromaddress) . '</p>';
  $html .= '<p>To: ' . htmlentities($headerInfo->toaddress) . '</p>';
  $html .= '<div style="background: lightgrey">' . (empty($mail->htmlText) ? ('<p>' . $mail->plainText . '</p>') : $mail->htmlText) . '</div>';
  return $html ;
}

function EmailDownload($host, $user, $password){
  $html = '<head> <meta charset="UTF-8"> </head>';
  $html .= '<h3>Simple imap client</h3>';
  $mails=EmailGetMany($host, $user, $password);
  $count=count($mails);
  $html .= "<p>$user has $count mails at $host.</p>";
  foreach ($mails as $mail){
      $html .= '<hr>';
      $html .= EmailAttachmentsSave($mail);
      $html .= EmailPrint($mail);
  }
  return $html ;
}
于 2020-02-03T11:23:43.130 回答