This article mainly introduces the SMTP mail sending class for PHP to support SSL connections. The example analyzes the principles and skills of php to implement the smtp mail sending class and the methods to support SSL connections, for more information, see
This article mainly introduces the SMTP mail sending class for PHP to support SSL connections. The example analyzes the principles and skills of php to implement the smtp mail sending class and the methods to support SSL connections, for more information, see
This example describes the SMTP mail sending class for PHP to support SSL connections. Share it with you for your reference. The details are as follows:
The instance code has tested SMTP In gmail and QQ mail. The Code is as follows:
The Code is as follows:
<? Php
/**
* Mail sending class
* Supports Sending plain text emails and HTML emails, including multiple recipients, multiple CC messages, multiple confidential CC messages, and attachments (one or more attachments). supports ssl connections to servers.
* Required php extensions: sockets, Fileinfo, and openssl.
* The encoding format is UTF-8, And the transfer encoding format is base64
* @ Example
* $ Mail = new MySendMail ();
* $ Mail-> setServer ("smtp@126.com", "XXXXX@126.com", "XXXXX"); // sets the smtp server, common connection mode
* $ Mail-> setServer ("smtp.gmail.com", "XXXXX@gmail.com", "XXXXX", 465, true); // set the SSL connection from the smtp server to the server
* $ Mail-> setFrom ("XXXXX"); // sets the sender
* $ Mail-> setReceiver ("XXXXX"); // sets the recipient. Multiple recipients are called multiple times.
* $ Mail-> setCc ("XXXX"); // sets CC, multiple CC, and multiple calls
* $ Mail-> setBcc ("XXXXX"); // sets the secret CC, multiple secret CC, and multiple calls
* $ Mail-> addAttachment ("XXXX"); // Add attachments, multiple attachments, multiple calls
* $ Mail-> setMail ("test ","Test"); // Set the subject and content of the email.
* $ Mail-> sendMail (); // send
*/
Class MySendMail {
/**
* @ Var string mail Transmission proxy Username
* @ Access protected
*/
Protected $ _ userName;
/**
* @ Var string the email transmission proxy Password
* @ Access protected
*/
Protected $ _ password;
/**
* @ Var string address of the mail Transmission Proxy Server
* @ Access protected
*/
Protected $ _ sendServer;
/**
* @ Var int port of the mail Transmission Proxy Server
* @ 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 private CC
* @ Access protected
*/
Protected $ _ bcc = array ();
/**
* @ Var string topic
* @ Access protected
*/
Protected $ _ subject;
/**
* @ Var string body of the email
* @ Access protected
*/
Protected $ _ body;
/**
* @ Var array attachment
* @ Access protected
*/
Protected $ _ attachment = array ();
/**
* @ Var reource socket Resource
* @ Access protected
*/
Protected $ _ socket;
/**
* @ Var reource is a secure connection
* @ Access protected
*/
Protected $ _ isSecurity;
/**
* @ Var string error message
* @ Access protected
*/
Protected $ _ errorMessage;
/**
* Set the mail Transmission proxy. If it is a server that can send emails anonymously, you only need to pass the proxy server address.
* @ Access public
* @ Param string $ ip address or domain name of the server Proxy server
* @ Param string $ username: authenticated account
* @ Param string $ password Authentication password
* @ Param int $ port indicates the port of the proxy server. smtp defaults to port 25.
* @ Param boolean $ whether the isSecurity connection to the server is a secure connection. The default value is 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 the sender
* @ Access public
* @ Param string $ from sender address
* @ Return boolean
*/
Public function setFrom ($ from ){
$ This-> _ from = $ from;
Return true;
}
/**
* Set recipients. Multiple recipients are called multiple times.
* @ Access public
* @ Param string $ to recipient address
* @ Return boolean
*/
Public function setReceiver ($ ){
$ This-> _ to [] = $;
Return true;
}
/**
* Sets CC and multiple CC requests. Multiple CC requests are called.
* @ Access public
* @ Param string $ cc address
* @ Return boolean
*/
Public function setCc ($ cc ){
$ This-> _ cc [] = $ cc;
Return true;
}
/**
* Sets a private cc. Multiple private CC messages are sent and called multiple times.
* @ Access public
* @ Param string $ bcc private CC address
* @ Return boolean
*/
Public function setBcc ($ bcc ){
$ This-> _ bcc [] = $ bcc;
Return true;
}
/**
* Set email attachments, multiple attachments, and call multiple times
* @ Access public
* @ Param string $ 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 email information
* @ Access public
* @ Param string $ body subject
* @ Param string $ content of the subject, 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 an 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;
}
}
// In fact, there is no need to close it here. The smtp command: After QUIT is sent, the server closes the connection and the local socket resources are automatically released.
$ This-> _ isSecurity? $ This-> closeSecutity (): $ this-> close ();
Return true;
}
/**
* Error message returned
* @ Return string
*/
Public function error (){
If (! Isset ($ this-> _ errorMessage )){
$ This-> _ errorMessage = "";
}
Return $ this-> _ errorMessage;
}
/**
* Return mail command
* @ Access protected
* @ Return array
*/
Protected function getCommand (){
$ Separator = "---- = _ Part _". md5 ($ this-> _ from. time (). uniqid (); // delimiter
$ Command = array (
Array ("HELO sendmail \ r \ n", 250)
);
If (! Empty ($ this-> _ userName )){
$ Command [] = array ("auth login \ r \ n", 334 );
$ Command [] = array ($ this-> _ userName. "\ r \ n", 334 );
$ Command [] = array ($ this-> _ password. "\ r \ n", 235 );
}
// Set the sender
$ Command [] = array ("mail from: <". $ this-> _ from. "> \ r \ n", 250 );
$ Header = "FROM: <". $ this-> _ from. "> \ r \ n ";
// Set the recipient
If (! Empty ($ this-> _ )){
$ Count = count ($ this-> _ );
If ($ count = 1 ){
$ Command [] = array ("rcpt to: <". $ this-> _ to [0]. "> \ r \ n", 250 );
$ Header. = "TO: <". $ this-> _ to [0]. "> \ r \ n ";
}
Else {
For ($ I = 0; $ I <$ count; $ I ++ ){
$ Command [] = array ("rcpt to: <". $ this-> _ to [$ I]. "> \ r \ n", 250 );
If ($ I = 0 ){
$ Header. = "TO: <". $ this-> _ to [$ I]. "> ";
}
Elseif ($ I + 1 ==$ count ){
$ Header. = ", <". $ this-> _ to [$ I]. "> \ r \ n ";
}
Else {
$ Header. = ", <". $ this-> _ to [$ I]. "> ";
}
}
}
}
// Set CC
If (! Empty ($ this-> _ cc )){
$ Count = count ($ this-> _ cc );
If ($ count = 1 ){
$ Command [] = array ("rcpt to: <". $ this-> _ cc [0]. "> \ r \ n", 250 );
$ Header. = "CC: <". $ this-> _ cc [0]. "> \ r \ n ";
}
Else {
For ($ I = 0; $ I <$ count; $ I ++ ){
$ Command [] = array ("rcpt to: <". $ this->_cc [$ I]. "> \ r \ n", 250 );
If ($ I = 0 ){
$ Header. = "CC: <". $ this-> _ cc [$ I]. "> ";
}
Elseif ($ I + 1 ==$ count ){
$ Header. = ", <". $ this-> _ cc [$ I]. "> \ r \ n ";
}
Else {
$ Header. = ", <". $ this-> _ cc [$ I]. "> ";
}
}
}
}
// Set secret CC
If (! Empty ($ this-> _ bcc )){
$ Count = count ($ this-> _ bcc );
If ($ count = 1 ){
$ Command [] = array ("rcpt to: <". $ this-> _ bcc [0]. "> \ r \ n", 250 );
$ Header. = "BCC: <". $ this-> _ bcc [0]. "> \ r \ n ";
}
Else {
For ($ I = 0; $ I <$ count; $ I ++ ){
$ Command [] = array ("rcpt to: <". $ this->_bcc [$ I]. "> \ r \ n", 250 );
If ($ I = 0 ){
$ Header. = "BCC: <". $ this-> _ bcc [$ I]. "> ";
}
Elseif ($ I + 1 ==$ count ){
$ Header. = ", <". $ this-> _ bcc [$ I]. "> \ r \ n ";
}
Else {
$ Header. = ", <". $ this-> _ bcc [$ I]. "> ";
}
}
}
}
// Subject
$ Header. = "Subject: =? UTF-8? B? ". $ This-> _ subject ."? = \ R \ n ";
If (isset ($ this-> _ attachment )){
// Declare the email header containing the attachment as this
$ Header. = "Content-Type: multipart/mixed; \ r \ n ";
}
Elseif (false ){
// If the email body contains image resources and the images contained in the email are declared as this in the email, it is not required if the referenced remote image is used.
$ Header. = "Content-Type: multipart/related; \ r \ n ";
}
Else {
// An html or plain text email is declared as this
$ Header. = "Content-Type: multipart/alternative; \ r \ n ";
}
// Mail header Separator
$ Header. = "\ t". 'boundary = "'. $ separator .'"';
$ Header. = "\ r \ nMIME-Version: 1.0 \ r \ n ";
// At the beginning, the body part of the email is divided into several parts for sending.
$ Header. = "\ r \ n --". $ separator. "\ r \ n ";
$ Header. = "Content-Type: text/html; charset = UTF-8 \ r \ n ";
$ Header. = "Content-Transfer-Encoding: base64 \ r \ n ";
$ Header. = $ this-> _ body. "\ r \ n ";
$ Header. = "--". $ separator. "\ r \ n ";
// Add the attachment
If (! Empty ($ this-> _ attachment )){
$ Count = count ($ this-> _ attachment );
For ($ I = 0; $ I <$ count; $ I ++ ){
$ Header. = "\ r \ n --". $ separator. "\ r \ n ";
$ Header. = "Content-Type:". $ this-> getMIMEType ($ this-> _ attachment [$ I]). ';'. "\ r \ n ";
$ Header. = "Content-Transfer-Encoding: base64 \ r \ n ";
$ Header. = 'content-Disposition: attachment; filename = "=? UTF-8? B? '. Base64_encode (basename ($ this-> _ attachment [$ I]).'? = "'." \ R \ n ";
$ Header. = "\ r \ n ";
$ Header. = $ this-> readFile ($ this-> _ attachment [$ I]);
$ Header. = "\ r \ n --". $ separator. "\ r \ n ";
}
}
// End email data sending
$ Header. = "\ r \ n. \ r \ n ";
$ Command [] = array ("DATA \ r \ n", 354 );
$ Command [] = array ($ header, 250 );
$ Command [] = array ("QUIT \ r \ n", 221 );
Return $ command;
}
/**
* Send command
* @ Access protected
* @ Param string $ smtp command sent by command to the server
* @ Param int $ code: Do you want the server to return a response?
* @ Return boolean
*/
Protected function sendCommand ($ command, $ code ){
Echo 'send command: '. $ command.', expected code: '. $ code .'
';
// Send a command to the server
Try {
If (socket_write ($ this-> _ socket, $ command, strlen ($ command ))){
// When the email content is sent multiple times, no $ code is returned and the server does not return
If (empty ($ code )){
Return true;
}
// Read the Server Response
$ 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 command through secure connection
* @ Access protected
* @ Param string $ smtp command sent by command to the server
* @ Param int $ code: Do you want the server to return a response?
* @ 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, no $ code is returned and the server does not return
If (empty ($ code )){
Return true;
}
// Read the Server Response
$ 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 content of the attachment file and return the base64-encoded file content.
* @ Access protected
* @ Param string $ 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;
}
}
/**
* Obtain the MIME type of the attachment.
* @ Access protected
* @ Param string $ 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 (){
// Create a socket Resource
$ 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); // sets the blocking mode.
// Connect to the server
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 an SSL network connection to the 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;
}
// Set the encrypted connection. The default value is ssl. If you need a tls connection, you can view the stream_socket_enable_crypto function in the php manual.
Stream_socket_enable_crypto ($ this-> _ socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT );
Stream_set_blocking ($ this-> _ socket, 1); // sets the blocking mode.
$ Str = fread ($ this-> _ socket, 1024 );
If (! Preg_match ("/220 +? /", $ Str )){
$ This-> _ errorMessage = $ str;
Return false;
}
Return true;
}
/**
* Disable 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 be close ";
Return false;
}
/**
* Disable Secure socket
* @ Access protected
* @ Return boolean
*/
Protected function closecutity (){
If (isset ($ this-> _ socket) & is_object ($ this-> _ socket )){
Stream_socket_shutdown ($ this-> _ socket, STREAM_SHUT_WR );
Return true;
}
$ This-> _ errorMessage = "No resource can be close ";
Return false;
}
}
I hope this article will help you with php programming.