从PHP中下载Gmail附件

3

您好,您想知道如何使用PHP从Gmail帐户下载附件吗?

谢谢。

3个回答

3

您可以使用PHP的POP或IMAP客户端来获取邮件并从中提取附件。


3
IMAP比POP更好,而且Gmail支持IMAP。 - Svisstack

3
如其他回答者所述,建议使用IMAP解决方案,可以在http://davidwalsh.name/gmail-php-imap找到。请确保检查您的防火墙,并在您的PHP安装中启用OpenSSL和IMAP。

http://www.electrictoolbox.com/extract-attachments-email-php-imap/有关于如何使用imap_fetchstructure分析每封电子邮件结构的优秀代码参考。在每个消息的结构中都包含附件。用户提供的笔记在http://www.php.net/manual/en/function.imap-fetchstructure.php上特别有帮助(文档也是如此)。

基本上,您需要:

  • 循环遍历结构部分
  • 确定哪些是附件
  • 根据需要进行解码。

不同的电子邮件客户端会有稍微不同的结构,但只要稍加努力就不难处理数据。然后可以以任何您选择的方式处理这些数据。


1

IMAP 解决方案

/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'davidwalshblog@gmail.com';
$password = 'davidwalsh';

/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . 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,2);

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

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

    echo $output;
} 

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

你必须添加附件控件,你可以阅读这个源代码 http://davidwalsh.name/gmail-php-imap


1
-1 这是重复的代码,没有解决原始问题,即关于附件的问题(“如何使用PHP从Gmail帐户下载附件?”)。你说“添加附件控件”,但是...怎么做? - Ben
@Steve:从这个点开始,您可以使用少量代码并结合 PHP 文档下载您想要的附件。如果您不相信,请看绿色标记。 - Svisstack
对不起Svisstack,我必须同意@Ben的观点:这段代码没有下载附件。你提出的链接并没有提供任何关于下载附件的代码。 - Marco Panichi

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