PHP implements SMTP mail delivery classes that support SSL connections

Source: Internet
Author: User
Tags base64 fread getmessage readfile socket trim server port ssl connection

This article mainly introduced the PHP implementation to support SSL connection SMTP mail send class, the example analyzes the PHP implementation SMTP mail sends the class the principle and the technique, as well as the support SSL connection method, needs the friend to be possible to refer to under

-->

The example in this article describes the SMTP mail delivery class for PHP implementations that support SSL connections. Share to everyone for your reference. Specifically as follows:

This instance code tests the SMTP of Gmail and QQ mailboxes. The specific code is as follows:

The code is as follows: <?php
/**
* Mail Send Class
* Support to send plain text mail and HTML format mail, can be multiple recipients, CC, multi-secret CC, with attachment (single or multiple attachments), support to the server's SSL connection
* 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 mode
* $mail->setserver ("smtp.gmail.com", "XXXXX@gmail.com", "XXXXX", 465, true); Set up an SMTP server, SSL connection to the server
* $mail->setfrom ("XXXXX"); Set Sender
* $mail->setreceiver ("XXXXX"); Set recipients, multiple recipients, calls multiple times
* $mail-&GT;SETCC ("XXXX"); Set CC, multiple cc, call multiple times
* $mail->setbcc ("XXXXX"); Set Secret CC, multiple secret cc, call multiple times
* $mail->addattachment ("XXXX"); Adding attachments, multiple attachments, calling multiple times
* $mail->setmail ("Test", "<b>test</b>"); Set message subject, content
* $mail->sendmail (); Send
*/
Class Mysendmail {
/**
* @var String message transfer agent user name
* @access protected
*/
protected $_username;
/**
* @var String message transfer agent password
* @access protected
*/
protected $_password;
/**
* @var String message transfer Proxy server address
* @access protected
*/
protected $_sendserver;
/**
* @var int message transfer proxy server port
* @access protected
*/
protected $_port;
/**
* @var String Sender
* @access protected
*/
protected $_from;
/**
* @var Array Recipients
* @access protected
*/
Protected $_to = Array ();
/**
* @var Array cc
* @access protected
*/
Protected $_CC = Array ();
/**
* @var array Secret cc
* @access protected
*/
Protected $_BCC = Array ();
/**
* @var String theme
* @access protected
*/
protected $_subject;
/**
* @var String message body
* @access protected
*/
protected $_body;
/**
* @var Array Accessories
* @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 up the message transfer agent, if the server can send the mail anonymously, just pass the proxy server address on the line
* @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 25th
* @param boolean $isSecurity 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 the recipient, multiple recipients, called multiple times.
* @access Public
* @param string $to recipient address
* @return Boolean
*/
Public Function Setreceiver ($to) {
$this->_to[] = $to;
return true;
}
/**
* Set CC, multiple cc, called multiple times.
* @access Public
* @param string $CC cc address
* @return Boolean
*/
Public Function SETCC ($CC) {
$this->_cc[] = $CC;
return true;
}
/**
* Set Secret CC, multiple secret cc, call multiple times
* @access Public
* @param string $BCC a secret cc address
* @return Boolean
*/
Public Function SETBCC ($BCC) {
$this->_bcc[] = $BCC;
return true;
}
/**
* Set up mail attachment, 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 Mail information
* @access Public
* @param string $body message subject
* @param string $subject The content of the message body, either 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 mail
* @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;
}
}
There's no need to shut down, SMTP command: After the quit issue, the server closes the connection and the local socket resource is automatically released
$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;
}
/**
* Back to Mail command
* @access protected
* @return Array
*/
protected function GetCommand () {
$separator = "----=_part_". MD5 ($this->_from. Time ()). Uniqid (); Separator
$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);
}
Set Sender
$command [] = Array ("MAIL from: <".) $this->_from. ">rn", 250);
$header = "From: <". $this->_from. ">rn";
Set recipient
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]. " > ";
}
}
}
}
Set CC
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]. " > ";
}
}
}
}
Set up Secret CC
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]. " > ";
}
}
}
}
Theme
$header. = "Subject: =? UTF-8? B? ". $this->_subject. "? =rn ";
if (Isset ($this->_attachment)) {
Message headers containing attachments need to be declared as this
$header. = "Content-type:multipart/mixed;rn";
}
ElseIf (False) {
The message body contains the picture resources, and contains the picture in the message inside the declaration as this, if it is a remote picture of the reference, you do not need
$header. = "Content-type:multipart/related;rn";
}
else{
HTML or plain text mail declaration as this
$header. = "Content-type:multipart/alternative;rn";
}
Message header Separator
$header. = "T". ' boundary= '. $separator. '"';
$header. = "Rnmime-version:1.0rn";
This starts with the body part of the message, and the body part is sent in several paragraphs.
$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 to 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 Mail Data send
$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 Expect the server to return a response?
* @return Boolean
*/
protected function SendCommand ($command, $code) {
Echo ' Send command: '. $command. ', expected code: '. $code. ' <br/> ';
Send command to Server
try{
if (Socket_write ($this->_socket, $command, strlen ($command)) {
When the content of the message is sent multiple times without $code, the server does not return
if (empty ($code)) {
return true;
}
Read Server return
$data = Trim (Socket_read ($this->_socket, 1024));
Echo ' response: '. $data. ' <br/><br/> ';
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 ();
}
}
/**
* Secure Connection Send command
* @access protected
* @param string $command SMTP command sent to the server
* @param int $code Expect the server to return a response?
* @return Boolean
*/
protected function sendcommandsecurity ($command, $code) {
Echo ' Send command: '. $command. ', expected code: '. $code. ' <br/> ';
try {
if (fwrite ($this->_socket, $command)) {
When the content of the message is sent multiple times without $code, the server does not return
if (empty ($code)) {
return true;
}
Read Server return
$data = Trim (fread ($this->_socket, 1024));
Echo ' response: '. $data. ' <br/><br/> ';
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 contents of the attachment file, return 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 the 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 () {
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);//Set blocking mode
Connecting to a 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 up an encrypted connection, the default is SSL, and if you need a TLS connection, you can view the explanation of the PHP manual Stream_socket_enable_crypto function
Stream_socket_enable_crypto ($this->_socket, True, stream_crypto_method_sslv23_client);
Stream_set_blocking ($this->_socket, 1); Set blocking mode
$str = Fread ($this->_socket, 1024);
if (!preg_match ("/220+?/", $str)) {
$this->_errormessage = $str;
return false;
}
return true;
}
/**
* Close 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;
}
}

I hope this article will help you with your PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.