PHP implements the mail sending instance code based on the SMTP protocol and smtp mail sending

Source: Internet
Author: User

PHP implements the mail sending instance code based on the SMTP protocol and smtp mail sending

SMTP protocol

When we use a third-party library or tool class of PHP to send emails, do you have any questions:

Why can't we use someone else's library instead of writing php code for email discovery? How does php send mails?

First, we need to understand the basic principles of sending mail. This article implements mail sending Based on SMTP protocol.

SMTP (Simple Mail Transfer Protocol) is a Simple Mail transmission Protocol. Simply put, it defines a set of rules. We only need to follow this rule to tell the SMTP server the sender, recipient, content, and topic of the email to be sent.

The SMTP server then parses the information we sent according to this set of rules, and finally sends the mail.
Email servers such as 163 and qq provide SMTP services. We only need to connect to their SMTP server and 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. To learn about the whole process of email sending.

Send emails via telnet

In linux, we can use the telnet command to connect to the smtp service of port 163 and port 25 (generally, port 25 is used for smtp) to understand the transmission process of smtp.

telnet smtp.163.com 25 

The following result is displayed, indicating that the 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])

Then we run the following command to tell the other party where our identity came from.

HELO smtp.163.com

The other party will return a 250 OK message.

Then execute auth login to tell the other party that we want to start identity authentication, and then the other party will respond to some of our messages.

Next we will enter our username, password, content of the sent email, sender, receiver, and other information, and then end the conversation. The smtp server will help us send the email.

Because the smtp protocol has strict requirements on the mail content format and is not easy to execute in the command line, the entire process is not completed here, and php code will be fully implemented later.

As you can see from the above process of using telnet to connect to smtp mail, the mail sending process is actually very simple, that is, to connect to port 25 of the smtp service and tell the recipient What mail we want to send according to the protocol. This has nothing to do with the platform and programming language.

Whether we use C, Java, or PHP, we can send emails as long as we connect to the SMTP server through Socket.

SMTP commands

When we used telnet to connect to the smtp service, we entered some HELO, auth login, etc. You may be wondering what these are.

In fact, these are the commands or rules defined by the SMTP protocol. The smtp server knows what we want to do through these commands.

Common commands are as follows:

Command Function
HELO A command sent to the recipient's email server to identify itself
AUTH LOGIN Coming soon for Identity Authentication
MAIL FROM Tell the recipient who sent the email
RCPT To whom
DATA Tell the recipient about this email. Next we will send the specific content of the email.
QUIT After the email content is entered, execute this command to exit

Php implements email sending

Directly Add code

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); // the user name and password must be base64 encoded. $ this-> pass = base64_encode ($ pass ); $ this-> debug = $ debug; // socket connection $ this-> sock = fsockopen ($ this-> host, $ this-> Port); if (! $ This-> sock) {exit ('error');} // read the data returned to us by the smtp service $ response = fgets ($ this-> sock ); $ this-> debug ($ response); // if the response contains a 220 return code, it indicates that the connection is successful if (strstr ($ response, '000000') === false) {exit ('error') ;}// send the SMTP command. The return code of different commands may be different from that of public function execCommand ($ cmd, $ return_code) {fwrite ($ this-> sock, $ cmd); $ response = fgets ($ this-> sock); // output debugging information $ this-> debug ('cmd: '. $ cmd. '; response :'. $ response); if (strstr ($ response, $ return_code) ===false) {return false;} return true;} public function sendMail ($ from, $, $ subject, $ body) {// detail is the content of the email, which must be in strict accordance with the following format. This is what the agreement stipulates: $ detail = 'from :'. $ from. "\ r \ n"; $ detail. = 'to :'. $. "\ r \ n"; $ detail. = 'subject :'. $ subject. "\ r \ n"; $ detail. = 'content-Type: Text/html ;'. "\ r \ n"; $ detail. = 'charset = gb2312 '. "\ 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: <". $. "> \ 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 );}}

Call example

$ Port = 25; $ user = 'username'; // replace it with your smtp username $ pass = 'pass '; // replace it with your smtp password $ host = 'smtp .163.com '; $ from = 'xxxxx @ 163.com'; $ to = 'xxxx @ qq.com '; $ body = 'Hello world'; $ subjet = 'I am title'; $ mailer = new Mailer ($ host, $ port, $ user, $ pass, true ); $ mailer-> sendMail ($ from, $ to, $ subjet, $ body );

The debugging information is output when the command is executed, and the response data that the smtp service returns to us is output every time the command is executed.

Therefore, we can see the following results

Debug: 220 163.com Anti-spam GT for Coremail System (163com [20141201]) Debug: cmd: HELO smtp.163.com; response: 250 OKDebug: cmd: auth login; response: 334 dXNlcm5hbWU6Debug: cmd: warn; response: 334 UGFzc3dvcmQ6Debug: cmd: Warn =; response: 235 Authentication successfulDebug: cmd: mail from:; response: 250 Mail OKDebug: cmd: rcpt: <380472723@qq.com>; response: 250 Mail OKDebug: cmd: DATA; response: 354 End data. debug: cmd: From: itzhoujunblog@163.com To: 380472723@qq.com Subject: I'm title Content-Type: Text/html; charset = gb2312 hello world .; response: 250 Mail OK queued as smtp11, D8CowACXHE5APdNYCo0hAQ --. 19144S2 1490238785 Debug: cmd: QUIT; response: 221 Bye

Summary

Email sending procedure

  1. Use socket to connect to the smtp service
  2. Use smtp commands for dialog, input identity information, mail information, etc.
  3. End conversation

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.