xai1981's blog

http://twitter.com/xai1981

PEAR Net_POP3 を使ってメール受信

PHPでメールを受信する必要がありましたので、下記を行いました。

PEAR Net_POP3 install

[root@kabosu ~]# pear install Net_POP3
WARNING: channel "pear.php.net" has updated its protocols, use "pear channel-update pear.php.net" to update
WARNING: "pear/Auth_SASL" is deprecated in favor of "pear/Auth_SASL2"
downloading Net_POP3-1.3.8.tgz ...
Starting to download Net_POP3-1.3.8.tgz (9,657 bytes)
.....done: 9,657 bytes
install ok: channel://pear.php.net/Net_POP3-1.3.8

テストPG

[root@kabosu /var/www/html]# cat MailReceiver.php
<?php
require_once 'Net/POP3.php';

Class MailReceiver
{
    private $pop;

    const HOST = 'ssl://pop.gmail.com';
    const PORT = 995;
    const USER = 'akira.xxx';
    const PASSWORD = 'xxxxxxxx';

    public function __construct()
    {
        $this->pop = new Net_POP3();

        $connectRet = $this->pop->connect(self::HOST, self::PORT);
        if (PEAR::isError($connectRet)) {
            echo 'connect error' . "\n";
            exit;
        }

        $loginRet = $this->pop->login(self::USER, self::PASSWORD);
        if (PEAR::isError($loginRet)) {
            echo 'login error' . "\n";
            exit;
        }

        echo print_r($this->pop->getListing(), true) . "\n";

        $message = $this->pop->getListing();
        if ($message) {
            foreach($message as $m) {
                echo 'id:' . $m['msg_id'] . "\n";
            }
        }
    }
}
$mr = new MailReceiver();

実行結果

[root@kabosu /var/www/html]# php MailReceiver.php
Array
(
    [0] => Array
        (
            [msg_id] => 1
            [size] => 1797
            [uidl] => GmailIdXXXXXXXXXXXXXXXX
        )

    [1] => Array
        (
            [msg_id] => 2
            [size] => 1797
            [uidl] => GmailIdXXXXXXXXXXXXXXXX
        )

    [2] => Array
        (
            [msg_id] => 3
            [size] => 3132
            [uidl] => GmailIdXXXXXXXXXXXXXXXX
        )
)

id:1
id:2
id:3

ただこのモジュール、環境によっては動きませんでした。だいぶ古い物のようですので下記の Zend/Mail を使った方が良いようです。

http://framework.zend.com/manual/2.0/en/modules/zend.mail.read.html