


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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
