Home >Backend Development >PHP Tutorial >PHP implements SMTP email sending class that supports SSL connection_PHP tutorial

PHP implements SMTP email sending class that supports SSL connection_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:05:051403browse

PHP implements the SMTP email sending class that supports SSL connections

This article mainly introduces the PHP implementation of the SMTP email sending class that supports SSL connections, and analyzes the implementation of SMTP email sending in PHP For the principles and techniques of classes, as well as methods to support SSL connections, friends in need can refer to it

The example in this article describes how PHP implements the SMTP email sending class that supports SSL connections. Share it with everyone for your reference. The details are as follows:

This example code has tested the SMTP of gmail and QQ mailboxes. The specific code is as follows:

The code is as follows:

/**
* Email sending class
* Supports sending plain text emails and emails in HTML format, with multiple recipients, multiple CCs, multiple secret CCs, with attachments (single or multiple attachments), and supports SSL connections to the server
* Required php extensions: sockets, Fileinfo and openssl.
* The encoding format is UTF-8, and the transmission encoding format is base64
* @example
* $mail = new MySendMail();
* $mail->setServer("smtp@126.com", "XXXXX@126.com", "XXXXX"); //Set smtp server, normal connection method
* $mail->setServer("smtp.gmail.com", "XXXXX@gmail.com", "XXXXX", 465, true); //Set smtp server, SSL connection to the server
* $mail->setFrom("XXXXX"); //Set the sender
* $mail->setReceiver("XXXXX"); //Set recipients, multiple recipients, call multiple times
* $mail->setCc("XXXX"); //Set CC, multiple CCs, call multiple times
* $mail->setBcc("XXXXX"); //Set secret carbon copy, multiple secret carbon copies, call multiple times
* $mail->addAttachment("XXXX"); //Add attachments, multiple attachments, call multiple times
* $mail->setMail("test", "test"); //Set email subject and content
* $mail->sendMail(); //Send
*/
class MySendMail {
/**
* @var string Mail transfer agent username
* @access protected
*/
protected $_userName;
/**
* @var string Mail transfer agent password
* @access protected
*/
protected $_password;
/**
* @var string Mail transfer proxy server address
* @access protected
*/
protected $_sendServer;
/**
* @var int Mail transfer proxy server port
* @access protected
*/
protected $_port;
/**
* @var string sender
* @access protected
*/
protected $_from;
/**
* @var array recipient
* @access protected
*/
protected $_to = array();
/**
* @var array CC
* @access protected
*/
protected $_cc = array();
/**
* @var array secret carbon copy
* @access protected
*/
protected $_bcc = array();
/**
* @var string theme
* @access protected
*/
protected $_subject;
/**
* @var string Email text
* @access protected
*/
protected $_body;
/**
* @var array attachment
* @access protected
*/
protected $_attachment = array();
/**
* @var resource socket resource
* @access protected
*/
protected $_socket;
/**
* @var resource Is it a secure connection
* @access protected
*/
protected $_isSecurity;
/**
* @var string error message
* @access protected
*/
protected $_errorMessage;
/**
* Set up a mail transfer proxy. If it is a server that can send mail anonymously, just pass the proxy server address
* @access public
* @param string $server The IP or domain name of the proxy server
* @param string $username authentication account
* @param string $password authentication password
* @param int $port proxy server port, smtp default port 25
* @param boolean $isSecurity Whether the connection to the server is a secure connection, default false
* @return boolean
*/
public function setServer($server, $username="", $password="", $port=25, $isSecurity=false) {
$this->_sendServer = $server;
$this->_port = $port;
$this->_isSecurity = $isSecurity;
$this->_userName = empty($username) ? "" : base64_encode($username);
$this->_password = empty($password) ? "" : base64_encode($password);
return true;
}
/**
* Set sender
* @access public
* @param string $from sender address
* @return boolean
*/
public function setFrom($from) {
$this->_from = $from;
return true;
}
/**
* Set recipients, multiple recipients, call multiple times.
* @access public
* @param string $to recipient address
* @return boolean
*/
public function setReceiver($to) {
$this->_to[] = $to;
return true;
}
/**
* Set CC, multiple CCs, call multiple times.
* @access public
* @param string $cc CC address
* @return boolean
*/
public function setCc($cc) {
$this->_cc[] = $cc;
return true;
}
/**
* Set up secret carbon copy, multiple secret carbon copies, call multiple times
* @access public
* @param string $bcc Secret carbon copy address
* @return boolean
*/
public function setBcc($bcc) {
$this->_bcc[] = $bcc;
return true;
}
/**
* Set email attachments, multiple attachments, call multiple times
* @access public
* @param string $file file address
* @return boolean
*/
public function addAttachment($file) {
if(!file_exists($file)) {
$this->_errorMessage = "file " . $file . " does not exist.";
return false;
}
$this->_attachment[] = $file;
return true;
}
/**
* Set up email information
* @access public
* @param string $body Email subject
* @param string $subject The main content of the email, which can be plain text or HTML text
* @return boolean
*/
public function setMail($subject, $body) {
$this->_subject = base64_encode($subject);
$this->_body = base64_encode($body);
return true;
}
/**
* Send email
* @access public
* @return boolean
*/
public function sendMail() {
$command = $this->getCommand();
$this->_isSecurity ? $this->socketSecurity() : $this->socket();
foreach ($command as $value) {
$result = $this->_isSecurity ? $this->sendCommandSecurity($value[0], $value[1]) : $this->sendCommand($value[0], $value[1]);
if($result) {
continue;
}
else{
return false;
}
}
//其实这里也没必要关闭,smtp命令:QUIT发出之后,服务器就关闭了连接,本地的socket资源会自动释放
$this->_isSecurity ? $this->closeSecutity() : $this->close();
return true;
}
/**
* Return error message
* @return string
*/
public function error(){
if(!isset($this->_errorMessage)) {
$this->_errorMessage = "";
}
return $this->_errorMessage;
}
/**
* Return to mail command
* @access protected
* @return array
*/
protected function getCommand() {
$separator = "----=_Part_" . md5($this->_from . time()) . uniqid(); //分隔符
$command = array(
array("HELO sendmailrn", 250)
);
if(!empty($this->_userName)){
$command[] = array("AUTH LOGINrn", 334);
$command[] = array($this->_userName . "rn", 334);
$command[] = array($this->_password . "rn", 235);
}
//设置发件人
$command[] = array("MAIL FROM: <" . $this->_from . ">rn", 250);
$header = "FROM: <" . $this->_from . ">rn";
//设置收件人
if(!empty($this->_to)) {
$count = count($this->_to);
if($count == 1){
$command[] = array("RCPT TO: <" . $this->_to[0] . ">rn", 250);
$header .= "TO: <" . $this->_to[0] .">rn";
}
else{
for($i=0; $i<$count; $i++){
$command[] = array("RCPT TO: <" . $this->_to[$i] . ">rn", 250);
if($i == 0){
$header .= "TO: <" . $this->_to[$i] .">";
}
elseif($i + 1 == $count){
$header .= ",<" . $this->_to[$i] .">rn";
}
else{
$header .= ",<" . $this->_to[$i] .">";
}
}
}
}
//设置抄送
if(!empty($this->_cc)) {
$count = count($this->_cc);
if($count == 1){
$command[] = array("RCPT TO: <" . $this->_cc[0] . ">rn", 250);
$header .= "CC: <" . $this->_cc[0] .">rn";
}
else{
for($i=0; $i<$count; $i++){
$command[] = array("RCPT TO: <" . $this->_cc[$i] . ">rn", 250);
if($i == 0){
$header .= "CC: <" . $this->_cc[$i] .">";
}
elseif($i + 1 == $count){
$header .= ",<" . $this->_cc[$i] .">rn";
}
else{
$header .= ",<" . $this->_cc[$i] .">";
}
}
}
}
//设置秘密抄送
if(!empty($this->_bcc)) {
$count = count($this->_bcc);
if($count == 1) {
$command[] = array("RCPT TO: <" . $this->_bcc[0] . ">rn", 250);
$header .= "BCC: <" . $this->_bcc[0] .">rn";
}
else{
for($i=0; $i<$count; $i++){
$command[] = array("RCPT TO: <" . $this->_bcc[$i] . ">rn", 250);
if($i == 0){
$header .= "BCC: <" . $this->_bcc[$i] .">";
}
elseif($i + 1 == $count){
$header .= ",<" . $this->_bcc[$i] .">rn";
}
else{
$header .= ",<" . $this->_bcc[$i] .">";
}
}
}
}
//Topic
$header .= "Subject: =?UTF-8?B?" . $this->_subject ."?=rn";
if(isset($this->_attachment)) {
//Email headers containing attachments need to be declared as this
$header .= "Content-Type: multipart/mixed;rn";
}
elseif(false){
//The email body contains image resources, and the included image is declared as this when it is inside the email. If it is a referenced remote image, it is not needed
$header .= "Content-Type: multipart/related;rn";
}
else{
//html or plain text emails are declared as this
$header .= "Content-Type: multipart/alternative;rn";
}
//Email header delimiter
$header .= "t" . 'boundary="' . $separator . '"';
$header .= "rnMIME-Version: 1.0rn";
//Here begins the body part of the email. The body part is divided into several paragraphs and sent
$header .= "rn--" . $separator . "rn";
$header .= "Content-Type:text/html; charset=utf-8rn";
$header .= "Content-Transfer-Encoding: base64rnrn";
$header .= $this->_body . "rn";
$header .= "--" . $separator . "rn";
//Add attachment
if(!empty($this->_attachment)){
$count = count($this->_attachment);
for($i=0; $i<$count; $i++){
$header .= "rn--" . $separator . "rn";
$header .= "Content-Type: " . $this->getMIMEType($this->_attachment[$i]) . '; name="=?UTF-8?B?' . base64_encode( basename($ this->_attachment[$i]) ) . '?="' . "rn";
$header .= "Content-Transfer-Encoding: base64rn";
$header .= 'Content-Disposition: attachment; filename="=?UTF-8?B?' . base64_encode( basename($this->_attachment[$i]) ) . '?="' . "rn" ;
$header .= "rn";
$header .= $this->readFile($this->_attachment[$i]);
$header .= "rn--" . $separator . "rn";
}
}
//End email data sending
$header .= "rn.rn";

$command[] = array("DATArn", 354);
$command[] = array($header, 250);
$command[] = array("QUITrn", 221);
return $command;
}
/**
* Send command
* @access protected
* @param string $command SMTP command sent to the server
* @param int $code Is the response expected from the server
* @return boolean
*/
protected function sendCommand($command, $code) {
echo 'Send command:' . $command . ',expected code:' . $code . '
';
//Send command to server
try{
if(socket_write($this->_socket, $command, strlen($command))){
//When the email content is sent multiple times, there is no $code and the server does not return
if(empty($code)) {
return true;
}
//Read server returns
$data = trim(socket_read($this->_socket, 1024));
echo 'response:' . $data . '

';
if($data) {
$pattern = "/^".$code."+?/";
if(preg_match($pattern, $data)) {
return true;
}
else{
$this->_errorMessage = "Error:" . $data . "|**| command:";
return false;
}
}
else{
$this->_errorMessage = "Error:" . socket_strerror(socket_last_error());
return false;
}
}
else{
$this->_errorMessage = "Error:" . socket_strerror(socket_last_error());
return false;
}
}catch(Exception $e) {
$this->_errorMessage = "Error:" . $e->getMessage();
}
}
/**
* Send commands via secure connection
* @access protected
* @param string $command SMTP command sent to the server
* @param int $code Is the response expected from the server
* @return boolean
*/
protected function sendCommandSecurity($command, $code) {
echo 'Send command:' . $command . ',expected code:' . $code . '
';
try {
if(fwrite($this->_socket, $command)){
//When the email content is sent multiple times, there is no $code and the server does not return
if(empty($code)) {
return true;
}
//Read server returns
$data = trim(fread($this->_socket, 1024));
echo 'response:' . $data . '

';
if($data) {
$pattern = "/^".$code."+?/";
if(preg_match($pattern, $data)) {
return true;
}
else{
$this->_errorMessage = "Error:" . $data . "|**| command:";
return false;
}
}
else{
return false;
}
}
else{
$this->_errorMessage = "Error: " . $command . " send failed";
return false;
}
}catch(Exception $e) {
$this->_errorMessage = "Error:" . $e->getMessage();
}
}
/**
* Read the attachment file content and return the base64 encoded file content
* @access protected
* @param string $file file
* @return mixed
*/
protected function readFile($file) {
if(file_exists($file)) {
$file_obj = file_get_contents($file);
return base64_encode($file_obj);
}
else {
$this->_errorMessage = "file " . $file . " dose not exist";
return false;
}
}
/**
* Get attachment MIME type
* @access protected
* @param string $file file
* @return mixed
*/
protected function getMIMEType($file) {
if(file_exists($file)) {
$mime = mime_content_type($file);
/*if(! preg_match("/gif|jpg|png|jpeg/", $mime)){
$mime = "application/octet-stream";
}*/
return $mime;
}
else {
return false;
}
}
/**
* Establish a network connection to the server
* @access protected
* @return boolean
*/
protected function socket() {
//创建socket资源
$this->_socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
if(!$this->_socket) {
$this->_errorMessage = socket_strerror(socket_last_error());
return false;
}
socket_set_block($this->_socket);//设置阻塞模式
//连接服务器
if(!socket_connect($this->_socket, $this->_sendServer, $this->_port)) {
$this->_errorMessage = socket_strerror(socket_last_error());
return false;
}
$str = socket_read($this->_socket, 1024);
if(!preg_match("/220+?/", $str)){
$this->_errorMessage = $str;
return false;
}
return true;
}
/**
* Establish SSL network connection to server
* @access protected
* @return boolean
*/
protected function socketSecurity() {
$remoteAddr = "tcp://" . $this->_sendServer . ":" . $this->_port;
$this->_socket = stream_socket_client($remoteAddr, $errno, $errstr, 30);
if(!$this->_socket){
$this->_errorMessage = $errstr;
return false;
}
//设置加密连接,默认是ssl,如果需要tls连接,可以查看php手册stream_socket_enable_crypto函数的解释
stream_socket_enable_crypto($this->_socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
stream_set_blocking($this->_socket, 1); //设置阻塞模式
$str = fread($this->_socket, 1024);
if(!preg_match("/220+?/", $str)){
$this->_errorMessage = $str;
return false;
}
return true;
}
/**
* 关闭socket
* @access protected
* @return boolean
*/
protected function close() {
if(isset($this->_socket) && is_object($this->_socket)) {
$this->_socket->close();
return true;
}
$this->_errorMessage = "No resource can to be close";
return false;
}
/**
* Close secure socket
* @access protected
* @return boolean
*/
protected function closeSecutity() {
if(isset($this->_socket) && is_object($this->_socket)) {
stream_socket_shutdown($this->_socket, STREAM_SHUT_WR);
return true;
}
$this->_errorMessage = "No resource can to be close";
return false;
}
}

 

希望本文所述对大家的php程序设计有所帮助。

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/963978.htmlTechArticlePHP implements SMTP email sending class that supports SSL connection. This article mainly introduces PHP implementing SMTP email that supports SSL connection. Sending class, examples analyze the principles and techniques of php implementing SMTP mail sending class...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn