


PHP implements SMTP email sending class that supports SSL connection_PHP tutorial
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: _from . ">rn", 250);
$header = "FROM: _from . ">rn";
//设置收件人
if(!empty($this->_to)) {
$count = count($this->_to);
if($count == 1){
$command[] = array("RCPT TO: _to[0] . ">rn", 250);
$header .= "TO: _to[0] .">rn";
}
else{
for($i=0; $i $command[] = array("RCPT TO: _to[$i] . ">rn", 250);
if($i == 0){
$header .= "TO: _to[$i] .">";
}
elseif($i + 1 == $count){
$header .= ",_to[$i] .">rn";
}
else{
$header .= ",_to[$i] .">";
}
}
}
}
//设置抄送
if(!empty($this->_cc)) {
$count = count($this->_cc);
if($count == 1){
$command[] = array("RCPT TO: _cc[0] . ">rn", 250);
$header .= "CC: _cc[0] .">rn";
}
else{
for($i=0; $i $command[] = array("RCPT TO: _cc[$i] . ">rn", 250);
if($i == 0){
$header .= "CC: _cc[$i] .">";
}
elseif($i + 1 == $count){
$header .= ",_cc[$i] .">rn";
}
else{
$header .= ",_cc[$i] .">";
}
}
}
}
//设置秘密抄送
if(!empty($this->_bcc)) {
$count = count($this->_bcc);
if($count == 1) {
$command[] = array("RCPT TO: _bcc[0] . ">rn", 250);
$header .= "BCC: _bcc[0] .">rn";
}
else{
for($i=0; $i$command[] = array("RCPT TO: _bcc[$i] . ">rn", 250);
if($i == 0){
$header .= "BCC: _bcc[$i] .">";
}
elseif($i + 1 == $count){
$header .= ",_bcc[$i] .">rn";
}
else{
$header .= ",_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 $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程序设计有所帮助。

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.