search
HomeBackend DevelopmentPHP TutorialPHP uses sockets to implement SMTP to send emails, socketsmtp_PHP tutorial

php implements SMTP to send emails based on sockets, socketsmtp

This article describes the example of php based on sockets to implement SMTP to send emails. Share it with everyone for your reference. The specific analysis is as follows:

php uses socket to send emails through SMTP.
Using the php-sockets extension of php, you can send emails in plain text and html formats. The code is as follows:
Copy code The code is as follows:
/**
* Email sending class
* Supports sending plain text emails and HTML format emails
* @example
* $config = array(
* "from" => "*****",
* "to" => "***",
* "subject" => "test",
* "body" => "test",
* "username" => "***",
* "password" => "****",
* "isHTML" => true
* );
*
* $mail = new MySendMail();
*
* $mail->setServer("smtp.126.com");
*
* $mail->setMailInfo($config);
* if(!$mail->sendMail()) {
* echo $mail->error();
* return 1;
* }
*/
class MySendMail {
/**
* @var Mail transfer agent username
* @access private
​*/
Private $_userName;
/**
* @var Mail transfer agent password
* @access private
​*/
private $_password;
/**
* @var Mail transfer proxy server address
* @access protected
​*/
protected $_sendServer;
/**
* @var Mail transfer proxy server port
* @access protected
​*/
protected $_port=25;
/**
* @var sender
* @access protected
​*/
protected $_from;
/**
* @var recipient
* @access protected
​*/
protected $_to;
/**
* @var theme
* @access protected
​*/
protected $_subject;
/**
* @var Email text
* @access protected
​*/
protected $_body;
/**
* @var Is it an email in HTML format
* @access protected
​*/
Protected $_isHTML=false;
/**
* @var socket resource
* @access protected
​*/
protected $_socket;
/**
* @var Error message
* @access protected
​*/
protected $_errorMessage;
public function __construct($from="", $to="", $subject="", $body="", $server="", $username="", $password="",$isHTML=" ", $port="") {
          if(!empty($from)){
                $this->_from = $from;
}
           if(!empty($to)){
                 $this->_to = $to;
}
          if(!empty($subject)){
                   $this->_subject = $subject;
}
If(!empty($body)){
                 $this->_body = $body;
}
If(!empty($isHTML)){
                  $this->_isHTML = $isHTML;
}
           if(!empty($server)){
                  $this->_sendServer = $server;
}
           if(!empty($port)){
            $this->_port = $port;
        }
        if(!empty($username)){
            $this->_userName = $username;
        }
        if(!empty($password)){
            $this->_password = $password;
        }
    }
    /**
* Set up mail transfer agent
* @param string $server The IP or domain name of the proxy server
* @param int $port The port of the proxy server, SMTP default port 25
* @param int $localPort local port
* @return boolean
​*/
    public function setServer($server, $port=25) {
        if(!isset($server) || empty($server) || !is_string($server)) {
            $this->_errorMessage = "first one is an invalid parameter";
            return false;
        }
        if(!is_numeric($port)){
            $this->_errorMessage = "first two is an invalid parameter";
            return false;
        }
        $this->_sendServer = $server;
        $this->_port = $port;
        return true;
    }
    /**
* Set up email
* @access public
* @param array $config Email configuration information
* Contains verification information of email sender, recipient, subject, content, and email transfer agent
* @return boolean
​*/
    public function setMailInfo($config) {
        if(!is_array($config) || count($config)             $this->_errorMessage = "parameters are required";
            return false;
        }
        $this->_from = $config['from'];
        $this->_to = $config['to'];
        $this->_subject = $config['subject'];
        $this->_body = $config['body'];
        $this->_userName = $config['username'];
        $this->_password = $config['password'];
        if(isset($config['isHTML'])){
            $this->_isHTML = $config['isHTML'];
        }
        return true;
    }
    /**
* Send email
* @access public
* @return boolean
​*/
    public function sendMail() {
        $command = $this->getCommand();
        $this->socket();
        foreach ($command as $value) {
            if($this->sendCommand($value[0], $value[1])) {
                continue;
            }
            else{
                return false;
            }
        }
$this->close(); //In fact, there is no need to close here, the smtp command: after QUIT is issued, the server closes the connection, and the local socket resources will be automatically released
echo 'Mail OK!';
        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() {
If($this->_isHTML) {
              $mail = "MIME-Version:1.0rn";
              $mail .= "Content-type:text/html;charset=utf-8rn";
$mail .= "FROM:test_from . ">rn";
$mail .= "TO:_to . ">rn";
$mail .= "Subject:" . $this->_subject ."rnrn";
$mail .= $this->_body . "rn.rn";
}
        else{
$mail = "FROM:test_from . ">rn";
$mail .= "TO:_to . ">rn";
$mail .= "Subject:" . $this->_subject ."rnrn";
$mail .= $this->_body . "rn.rn";
}
         $command = array(
array("HELO sendmailrn", 250),
array("AUTH LOGINrn", 334),
array(base64_encode($this->_userName) . "rn", 334),
array(base64_encode($this->_password) . "rn", 235),
array("MAIL FROM:_from . ">rn", 250),
array("RCPT TO:_to . ">rn", 250),
array("DATArn", 354),
array($mail, 250),
array("QUITrn", 221)
);
         return $command;
}
/**
* @access protected
* @param string $command SMTP command sent to the server
* @param int $code Do you expect the response returned by the server
* @param 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))){
                //读取服务器返回
                $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();
        }
    }
    /**
* Establish a network connection to the server
* @access private
* @return boolean
​*/
    private function socket() {
        if(!function_exists("socket_create")) {
            $this->_errorMessage = "extension php-sockets must be enabled";
            return false;
        }
        //创建socket资源
        $this->_socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
        if(!$this->_socket) {
            $this->_errorMessage = socket_strerror(socket_last_error());
            return false;
        }
        //连接服务器
        if(!socket_connect($this->_socket, $this->_sendServer, $this->_port)) {
            $this->_errorMessage = socket_strerror(socket_last_error());
            return false;
        }
        socket_read($this->_socket, 1024);
        return true;
    }
    /**
    * 关闭socket
    * @access private
    * @return boolean
   */
    private 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;
    }
}
/**************************** Test ***********************************/
$config = array(
        "from" => "XXXXX",
        "to" => "XXXXX",
        "subject" => "test",
        "body" => "test",
        "username" => "XXXXX",
        "password" => "******",
        //"isHTML" => true
    );
$mail = new MySendMail();
$mail->setServer("smtp.126.com");
$mail->setMailInfo($config);
if(!$mail->sendMail()) {
    echo $mail->error();
    return 1;
}

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/963852.htmlTechArticlephp基于socket实现SMTP发送邮件的方法,socketsmtp 本文实例讲述了php基于socket实现SMTP发送邮件的方法。分享给大家供大家参考。具体分析如下:...
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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.