1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
$server = "smtp服务器"; $user = "发送邮箱"; $pass = "发送密码"; $separator = "----=_Part_" . md5($user . time()) . uniqid(); //分隔符 $command = array( array("HELO sendmail\r\n", 250) ); $command[] = array("AUTH LOGIN\r\n", 334); $command[] = array(base64_encode($user) . "\r\n", 334); $command[] = array(base64_encode($pass) . "\r\n", 235); //设置发件人 $command[] = array("MAIL FROM: <" . $user . ">\r\n", 250); $header = "FROM: 发送人<" . $user . ">\r\n"; //设置收件人 $command[] = array("RCPT TO: <" . $to . ">\r\n", 250); $header .= "TO: <" . $to .">\r\n"; //主题 $header .= "Subject: =?UTF-8?B?" . base64_encode($subject) ."?=\r\n"; $header .= "Content-Type: multipart/alternative;\r\n"; //邮件头分隔符 $header .= "\t" . 'boundary="' . $separator . '"'; $header .= "\r\nMIME-Version: 1.0\r\n"; //这里开始是邮件的body部分,body部分分成几段发送 $header .= "\r\n--" . $separator . "\r\n"; $header .= "Content-Type:text/html; charset=utf-8\r\n"; $header .= "Content-Transfer-Encoding: base64\r\n\r\n"; $header .= base64_encode($text) . "\r\n"; $header .= "--" . $separator . "\r\n"; $header .= "\r\n.\r\n"; $command[] = array("DATA\r\n", 354); $command[] = array($header, 250); $command[] = array("QUIT\r\n", 221); //创建socket资源 $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_set_block($socket);//设置阻塞模式 socket_connect($socket, $server, "25"); socket_read($socket, 1024); foreach ($command as $value) { //try{ if(socket_write($socket, $value[0], strlen($value[0]))){ //当邮件内容分多次发送时,没有$code,服务器没有返回 if(empty($value[1])) { return true; } //读取服务器返回 $data = trim(socket_read($socket, 1024)); //echo 'response:' . $data . '<br /><br />'; if($data) { $pattern = "/^".$value[1]."+?/"; if(preg_match($pattern, $data)) { $result = true; } else{ //$this->_errorMessage = "Error:" . $data . "|**| command:"; $result = false; } } else{ //$this->_errorMessage = "Error:" . socket_strerror(socket_last_error()); $result = false; } } else{ //$this->_errorMessage = "Error:" . socket_strerror(socket_last_error()); $result = false; } /*}catch(Exception $e) { echo "Error:" . $e->getMessage(); }*/ if($result) { continue; } else{ return false; } } |