如何从PHP获取电子邮件及其附件

18
我正在为朋友的婚礼编写一个照片库网站,并且他们希望有一个照片库让客人上传当天拍摄的数字照片。
在评估了所有选项之后,我决定最容易让用户使用的方法是让他们使用熟悉的界面(电子邮件),并只需将照片作为附件发送。
我已经创建了一个邮箱,但现在我需要连接并检索这些附件以进行自动处理,然后添加到图库系统中。但如何实现?您见过任何用于执行此操作的教程或预制类吗?
7个回答

10

我以前经常做这种事情,但现在找不到代码了,这里有一个我找到的缩小版。它应该可以让你走上正确的道路。我曾经从cronjob运行这种类型的脚本。很抱歉我找不到最终版本。

// Open pop mailbox
if (!$mbox = imap_open ("{localhost:110/pop3/notls}INBOX", "user", "tester")) {
  die ('Cannot connect/check pop mail! Exiting');
}

if ($hdr = imap_check($mbox)) {
  $msgCount = $hdr->Nmsgs;
} else {
  echo "Failed to get mail";
  exit;
}

$MN=$msgCount;
$overview=imap_fetch_overview($mbox,"1:$MN",0);

for ($X = 1; $X <= $MN; $X++) {

  $file = imap_fetchbody($mbox, $X, 1);

  imap_delete($mbox, $X);
}

imap_expunge($mbox);
imap_close($mbox);

祝你好运!


1
如果他们控制接收MTA,我认为更优雅的做法是将MTA交付给程序,而不是交付给IMAP服务器,因为这只是减少故障点。我承认这并不总是一个选项。 - Daniel Papasian

6

您是否考虑过使用谷歌的Picasa Web相册?您可以设置一个电子邮件地址来发送照片并在线共享它们。然后,您可以获取这些照片的RSS源,大多数程序员比MTAs更熟悉这种方式。


这是一个不错的替代方案!然而,Google建议不要分享您的秘密密钥,因此您可能希望通过将您的MTA别名指向某个地址来保护它,例如在您的别名文件中添加以下内容:msgsubmit: myusername.mysecretkey@picasaweb.com - Daniel Papasian
加一分给你,因为你有超越常规的思维。 - Nir Gavish

6
如果您为此目的创建了专用邮箱,则几乎肯定不希望使用过滤机制。相反,您希望邮箱成为应用程序的管道,并且应用程序仅从stdin读取消息,解析出正文并MIME解析正文以获取附件。
我所知道的所有流行的基于Unix的MTA(如sendmail,postfix和qmail)都支持将邮箱作为管道。通常,您可以在别名文件中定义它,如下所示:
# sendmail或postfix语法 msgsubmit:“| /usr/bin/php ~path/to/example.php”
然后,发送到msgsubmit@的邮件将路由到php程序进行传递。
这样做的好处是不依赖IMAP服务器或除MTA之外的任何其他服务器,只要您控制目标主机的MTA即可正常工作。如果您想要检查系统上的所有消息是否都被脚本检查,那么过滤就是您想要的,但我猜这不是您的情况。
如果您想要在某个地方保留副本(这不是一个坏主意),只需将别名定义为转到多个地址,如下所示:

msgsubmit: "| /usr/bin/php ~path/to/example.php", msgsubmit-box

或者后缀虚拟格式:

msgsubmit
    "| /usr/bin/php ~path/to/example.php"
    msgsubmit-box


4
你使用的是哪种MTA?如果你使用postfix + maildrop,你可以创建一个过滤规则,将某些消息通过PHP脚本进行管道传输,然后处理传入的邮件。(搜索maildrop和xfilter)。

是的,从我的角度来看,后缀路由似乎是一个不错的解决方案。谢谢! - Oli
这个方法更加优雅,但是我的主机似乎不支持它。看起来这个方法只在使用 cPanel 的主机上内置(也许是时候找另一个主机了)。 - Shanimal

1

我认为你需要一个MIME消息解析器。

我以前用过这个,似乎工作得很好,尽管我没有在真正大的附件上测试过(即从数码相机中可能获得的2-3MB文件)。

你已经有了一个读取POP3 / IMAP邮箱的系统吗?同一网站上还有另一个类也适用于POP3(我相信也有IMAP),但是如果你要下载大量邮件,也许你会想要研究一些基于C的解决方案,因为我相信那个纯PHP的解决方案可能不太适合。


0

Majordomo可能是处理电子邮件的替代方案,但在文件附件处理方面存在一些限制。


-4
<?php
//make sure that submit button name is 'Submit'
if(isset($_POST['Submit'])){


       $name = $_POST['visitorname'];
       $email = $_POST['visitoremail'];
       $message = $_POST['visitormessage'];


            $to="youremail@yourdomain.com";

          $subject="From ".$name;


          $from = $email;

          // generate a random string to be used as the boundary marker
          $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

          // now we'll build the message headers
          $headers = "From: $from\r\n" .
          "MIME-Version: 1.0\r\n" .
             "Content-Type: multipart/mixed;\r\n" .
             " boundary=\"{$mime_boundary}\"";

          // next, we'll build the invisible portion of the message body
          // note that we insert two dashes in front of the MIME boundary
          // when we use it
          $message = "This is a multi-part message in MIME format.\n\n" .
             "--{$mime_boundary}\n" .
             "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
             "Content-Transfer-Encoding: 7bit\n\n" .
          $message . "\n\n";

 foreach($_FILES as $userfile)
          {
             // store the file information to variables for easier access
             $tmp_name = $userfile['tmp_name'];
             $type = $userfile['type'];
             $name = $userfile['name'];
             $size = $userfile['size'];



             // if the upload succeded, the file will exist
             if (file_exists($tmp_name))
             {

                // check to make sure that it is an uploaded file and not a system file
                if(is_uploaded_file($tmp_name))
                {

                   // open the file for a binary read
                   $file = fopen($tmp_name,'rb');

                   // read the file content into a variable
                   $data = fread($file,filesize($tmp_name));

                   // close the file
                   fclose($file);

                   // now we encode it and split it into acceptable length lines
                   $data = chunk_split(base64_encode($data));
                }

                // now we'll insert a boundary to indicate we're starting the attachment
                // we have to specify the content type, file name, and disposition as
                // an attachment, then add the file content.
                // NOTE: we don't set another boundary to indicate that the end of the
                // file has been reached here. we only want one boundary between each file
                // we'll add the final one after the loop finishes.
                $message .= "--{$mime_boundary}\n" .
                   "Content-Type: {$type};\n" .
                   " name=\"{$name}\"\n" .
                   "Content-Disposition: attachment;\n" .
                   " filename=\"{$fileatt_name}\"\n" .
                   "Content-Transfer-Encoding: base64\n\n" .
                $data . "\n\n";
             }
          }


$ok = @mail($to, $subject, $message , $headers);
if ($ok) {
if (($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {

if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);

      }
    }
  }
else
  {

  }
echo "<span class='red'>E-mail has been sent successfully from $mail_name to $to</span>"; }
else{
echo "<span class='red'>Failed to send the E-mail from $from to $to</span>";
}
}
?>

附言:我使用了这段代码,希望它能够帮到你。只需复制并粘贴即可,确保你的文本字段名称与此页面相同。它适用于所有类型的文件。如果有进一步的问题,请发送电子邮件至shah@mc-oren.com。无论如何,我也在学习过程中。=)谢谢。


2
-1:楼主并不是在问如何发送电子邮件,而是想要检索它们。 - Shannon Matthews

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接