开发者

PHP: How to communicate with mail server thru SMTP?

How to communicate with m开发者_StackOverflow中文版ail server thru SMTP using PHP?


Open a socket using fsockopen. Write to the socket using fwrite. Read from the socket line by line using fgets or byte by byte using fread.


I wrote this snippet for the Email() method of my personal PHP framework, phunction, maybe it can be of some help. The regex I used is able to validate each individual reply from the SMTP server.

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;
}


Look up the documentation for mail().


Take a look at PHPMailer.


Maybe you are looking for this:

These examples use the 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


take a look at Zend_Mail it had every function needed to do with mail

-http://framework.zend.com

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜