PHP:如何通过SMTP与邮件服务器通信?

时间:2011-01-14 15:12:46

标签: php smtp

如何使用PHP通过SMTP与邮件服务器通信?

6 个答案:

答案 0 :(得分:2)

使用fsockopen打开套接字。使用fwrite写入套接字。使用fgets逐行读取套接字,或使用fread逐字节读取。

答案 1 :(得分:1)

我为我个人PHP framework, phunctionEmail()方法编写了此代码段,也许它可以提供一些帮助。我使用的正则表达式能够验证来自SMTP服务器的每个单独的回复。

if (isset($smtp) === true)
{
    $result = null;
    $stream = stream_socket_client($smtp);

    if (is_resource($stream) === true)
    {
        $data = array('HELO ' . $_SERVER['HTTP_HOST']);
        $result .= substr(ltrim(fread($stream, 8192)), 0, 3);

        if (preg_match('~^220~', $result) > 0)
        {
            $auth = array_slice(func_get_args(), 8, 2);

            if (count($auth) == 2)
            {
                $data = array_merge($data, array('AUTH LOGIN'), array_map('base64_encode', $auth));
            }

            $data[] = sprintf('MAIL FROM: <%s>', implode('', array_slice($from, 0, 1)));

            foreach (array_merge(array_values($to), array_values($cc), array_values($bcc)) as $value)
            {
                $data[] = sprintf('RCPT TO: <%s>', $value);
            }

            $data[] = 'DATA';
            $data[] = implode("\r\n", array_merge(array_diff_key($header, array('Bcc' => true)), array(''), $content, array('.')));
            $data[] = 'QUIT';

            while (preg_match('~^220(?>250(?>(?>334){1,2}(?>235)?)?(?>(?>250){1,}(?>354(?>250)?)?)?)?$~', $result) > 0)
            {
                if (fwrite($stream, array_shift($data) . "\r\n") !== false)
                {
                    $result .= substr(ltrim(fread($stream, 8192)), 0, 3);
                }
            }

            if (count($data) > 0)
            {
                if (fwrite($stream, array_pop($data) . "\r\n") !== false)
                {
                    $result .= substr(ltrim(fread($stream, 8192)), 0, 3);
                }
            }
        }

        fclose($stream);
    }

    return (preg_match('~221$~', $result) > 0) ? true : false;
}

答案 2 :(得分:0)

查找mail()的文档。

答案 3 :(得分:0)

看看PHPMailer

答案 4 :(得分:0)

也许你正在寻找这个:

这些示例使用Pear Mail Package:http://pear.php.net/package/Mail

http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm http://www.cyberciti.biz/tips/howto-php-send-email-via-smtp-authentication.html

答案 5 :(得分:0)

看看Zend_Mail它具有邮件所需的所有功能

-http://framework.zend.com

-http://framework.zend.com/manual/en/zend.mail.html

相关问题