$smtp = fsockopen('ssl://smtp.163.com', '465');
// 握手
$this->execute("EHLO " . $_SERVER['SERVER_NAME']);
// 登录验证
//如果是starttls协议则需要开启tls加密
$this->execute("STARTTLS");
stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
$this->execute("EHLO " . $_SERVER['SERVER_NAME']);
$this->execute("AUTH LOGIN");
$this->execute(base64_encode($username));
$this->execute(base64_encode($password));
// 发件人
$this->execute('MAIL FROM:<' . $username . ">");
// 收件人
foreach ($to as $t)
{
$this->execute('RCPT TO:<' . $t . ">");
}
// 抄送人
foreach ($cc as $c)
{
$this->execute('RCPT TO:<' . $c . ">");
}
// 邮件内容
$this->execute("DATA");
$body = 'From:' . $username . "\r\n";
foreach ($to as $t)
{
$body .= 'To:' . $t . "\r\n";
}
foreach ($cc as $c)
{
$body .= 'Cc:' . $c . "\r\n";
}
$boundary = 'part_' . uniqid();
$body .= 'Subject:' . $subject . "\r\n";
$body .= 'Date:' . date('Y-m-d H:i:s', time()) . "\r\n";
$body .= empty($in_reply_to) ? '' : ('In-Reply-To:' . $in_reply_to . "\r\n");
$body .= empty($references) ? '' : ('References:' . $references . "\r\n");
$body .= 'Content-Type: multipart/mixed; boundary=' . $boundary . "\r\n\r\n";
$body .= '--' . $boundary . "\r\n";
$body .= 'Content-Type: text/html; charset=utf-8;' . "\r\n";
$body .= 'Content-Transfer-Encoding: 8bit' . "\r\n\r\n";
$body .= $mails_body . "\r\n\r\n";
// 判断是否存在附件
if ( ! empty($attach))
{
foreach ($attach as $a)
{
$filename = isset($a['filename']) ? $a['filename'] : 'aaa.txt';
$content = isset($a['content']) ? $a['content'] : '';
$body .= '--' . $boundary . "\r\n";
$body .= 'Content-Type: application/octet-stream;charset=utf-8' . "\r\n";
$body .= 'Content-Transfer-Encoding: base64' . "\r\n";
$body .= 'Content-Disposition: attachment; filename="' . $filename . '"' . "\r\n\r\n";
$body .= $content . "\r\n\r\n";
}
}
$body .= '--' . $boundary . "--\r\n";
$body .= "\r\n.";
$this->execute($body);
$this->execute("QUIT");
//执行
private function execute($command)
{
fwrite($stream, $command . "\r\n");
$handle_status = fread($this->stream, 512);
if ($debug)
{
dump($command);
var_dump($handle_status);
}
$status = '/^(5|4)/';
if(preg_match($status, $handle_status, $matches))
{
return array('ack' => 'fail', 'message' => '邮件发送失败:' . $command . "\n" . $handle_status);
}
}
PHP MAILS SMTP 使用记录
最新推荐文章于 2023-06-07 17:59:39 发布