Home > Article > Backend Development > PHP method to implement email sending instance based on SMTP protocol
This article mainly introduces the example code of sending emails based on PHP based on SMTP protocol. It has certain reference value. Interested friends can refer to it
SMTP protocol
When we use PHP third-party libraries or tools to send emails, have you ever thought about a question:
Why can't we write PHP code ourselves to realize email discovery, but use other people's libraries? Woolen cloth? How to send emails in php?
First of all, we need to understand the basic principles of sending emails. This article implements email sending based on the SMTP protocol.
SMTP (Simple Mail Transfer Protocol) is a simple mail transfer protocol. Simply put, it defines a set of rules. We only need to follow these rules to tell the SMTP server that we want to send the sender, recipient, content, subject and other information of the email.
Then the SMTP server parses the information we send according to this set of rules, and finally sends the email.
Mail servers such as 163 and qq all provide SMTP services. We only need to connect to their SMTP servers and then write data to send emails.
In fact, we can directly use the Linux telnet tool to connect to the SMTP service and send emails without writing code. Use this to understand the entire process of sending emails.
Telnet to send emails
We can use the telnet command in the Linux environment to connect to the SMTP service of 163, port 25 (generally SMTP uses port 25) , to understand the SMTP transmission process.
telnet smtp.163.com 25
Then you will get the following results, indicating that our connection is successful
Trying 220.181.12.16... Connected to smtp.163.com. Escape character is '^]'. 220 163.com Anti-spam GT for Coremail System (163com[20141201])
Continue We execute the following command to tell the other party where our identity comes from
HELO smtp.163.com
The other party will return us a 250 OK
and then execute AUTH LOGIN Tell the other party that we want to start identity authentication, and then the other party will respond to us with some messages.
Later we will enter our user name, password, content of the email, sender, recipient and other information, then end the conversation, and the SMTP server will help us send the email.
Since the SMTP protocol has strict requirements on the format of email content and is difficult to execute on the command line, the entire process is not executed here, and will be fully implemented using PHP code later.
As can be seen from the above process of using telnet to connect to SMTP emails, the process of sending emails is actually very simple. It is to connect to port 25 of the SMTP service and tell the other party what email we want to send according to the protocol. This has nothing to do with platform or programming language.
Whether we use C language, Java or PHP, as long as we use Socket to connect to the SMTP server, we can send emails.
SMTP command
When we used telnet to connect to the SMTP service above, we entered some HELO, AUTH LOGIN, etc. You may have questions about what these are.
In fact, it is very simple. These are the instructions, or rules, defined by the SMTP protocol. It is through these instructions that the SMTP server knows what we want to do.
Commonly used instructions are as follows:
Command | Function |
---|---|
HELO | A command issued to the other party’s mail server to identify oneself |
AUTH LOGIN | Coming soon Perform identity authentication |
MAIL FROM | Tell the other party who the sender of this email is |
RCPT TO | Who to send to |
DATA | Tell the other party about this email, and then we will send the specific content of the email |
QUIT | After entering the email content, execute this command to exit |
php实现邮件发送
直接上代码
class Mailer { private $host; private $port = 25; private $user; private $pass; private $debug = false; private $sock; public function __construct($host,$port,$user,$pass,$debug = false) { $this->host = $host; $this->port = $port; $this->user = base64_encode($user); //用户名密码一定要使用base64编码才行 $this->pass = base64_encode($pass); $this->debug = $debug; //socket连接 $this->sock = fsockopen($this->host,$this->port); if(!$this->sock){ exit('出错啦'); } //读取smtp服务返回给我们的数据 $response = fgets($this->sock); $this->debug($response); //如果响应中有220返回码,说明我们连接成功了 if(strstr($response,'220') === false){ exit('出错啦'); } } //发送SMTP指令,不同指令的返回码可能不同 public function execCommand($cmd,$return_code){ fwrite($this->sock,$cmd); $response = fgets($this->sock); //输出调试信息 $this->debug('cmd:'.$cmd .';response:'.$response); if(strstr($response,$return_code) === false){ return false; } return true; } public function sendMail($from,$to,$subject,$body){ //detail是邮件的内容,一定要严格按照下面的格式,这是协议规定的 $detail = 'From:'.$from."\r\n"; $detail .= 'To:'.$to."\r\n"; $detail .= 'Subject:'.$subject."\r\n"; $detail .= 'Content-Type: Text/html;'."\r\n"; $detail .= 'charset=gb2312'."\r\n\r\n"; $detail .= $body; $this->execCommand("HELO ".$this->host."\r\n",250); $this->execCommand("AUTH LOGIN\r\n",334); $this->execCommand($this->user."\r\n",334); $this->execCommand($this->pass."\r\n",235); $this->execCommand("MAIL FROM:<".$from.">\r\n",250); $this->execCommand("RCPT TO:<".$to.">\r\n",250); $this->execCommand("DATA\r\n",354); $this->execCommand($detail."\r\n.\r\n",250); $this->execCommand("QUIT\r\n",221); } public function debug($message){ if($this->debug){ echo '<p>Debug:'.$message . PHP_EOL .'</p>'; } } public function __destruct() { fclose($this->sock); } }
调用示例
$port = 25; $user = 'username'; //请替换成你自己的smtp用户名 $pass = 'pass'; //请替换成你自己的smtp密码 $host = 'smtp.163.com'; $from = 'xxxxx@163.com'; $to = 'xxxx@qq.com'; $body = 'hello world'; $subjet = '我是标题'; $mailer = new Mailer($host,$port,$user,$pass,true); $mailer->sendMail($from,$to,$subjet,$body);
在执行指令时有输出调试信息,输出了我们每次执行的指令以及smtp服务返回给我们的响应数据。
因此我们可以看到以下结果
Debug:220 163.com Anti-spam GT for Coremail System (163com[20141201]) Debug:cmd:HELO smtp.163.com ;response:250 OK Debug:cmd:AUTH LOGIN ;response:334 dXNlcm5hbWU6 Debug:cmd:aXR6aG91anVuYmxvZ0AxNjMuY29t ;response:334 UGFzc3dvcmQ6 Debug:cmd:QzBjSGRRNe32xiNGFYUE5oag== ;response:235 Authentication successful Debug:cmd:MAIL FROM: ;response:250 Mail OK Debug:cmd:RCPT TO:<380472723@qq.com> ;response:250 Mail OK Debug:cmd:DATA ;response:354 End data with . Debug:cmd:From:itzhoujunblog@163.com To:380472723@qq.com Subject:我是标题 Content-Type: Text/html; charset=gb2312 hello world . ;response:250 Mail OK queued as smtp11,D8CowACXHE5APdNYCo0hAQ--.19144S2 1490238785 Debug:cmd:QUIT ;response:221 Bye
总结
邮件发送步骤
使用socket连接smtp服务
使用smtp指令进行对话,输入身份信息,邮件信息等
结束对话
以上就是本文的全部内容,希望对大家的学习有所帮助。
相关推荐:
The above is the detailed content of PHP method to implement email sending instance based on SMTP protocol. For more information, please follow other related articles on the PHP Chinese website!