Home  >  Article  >  Backend Development  >  Sending emails using Socket in PHP_PHP Tutorial

Sending emails using Socket in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 17:37:40820browse

Among the several PHP homepage spaces that the author has applied for, there are not many that can provide the mail function. It always fails after calling the mail() function
Nothing further. But the role of email in online life is getting bigger and bigger. I don’t want to talk about it anymore, but what should I do if the homepage space does not support mail() sending? I also thought about implementing email through socket
Send, but unfortunately I am not familiar with socket programming using PHP. In addition, sending emails requires using the SMTP protocol, and I need to read a lot of English, so
I have never studied it before. Finally one day I found an article about using socket programming to send emails. I copied it like a treasure
Download it and transform it into a class available in PHP for everyone to use. The original article was just a simple example, and there was one more
After many experiments and modifications, I finally changed it into a class that directly uses sockets to send emails to specified mailboxes, such as
If you combine it with the previous article about sending MIME, you can send emails on websites that do not support the mail() function. Because I posted
The process of sending emails takes time, and may not be exactly the same as the processing mechanism of mail(), so the speed is slower, but it can solve the need to send
The function of sending emails is urgently needed. At the same time, you can also learn to use php for socket programming. Next, I will introduce to you the implementation principle of this class,
At the same time, I will explain to you some basic knowledge about SMTP.

Introduction to Socket Programming
I would like to declare to everyone that I am not a TCP/IP programming expert, so I just share my understanding and experience here.

Use the fsockopen function to open an Internet connection. Function syntax format:

int fsockopen(string hostname, int port, int [errno], string [errstr], int [timeout]);

I don’t think I need to talk about the meaning of the parameters. Since the SMTP protocol is used here, the port number is 25. After the connection is successfully opened, a
will be returned A socket handle, which can be used like a file handle. The available operations are fputs(), fgets(), feof(), fclose()
wait.

That’s it for a very simple introduction.

Basics of SMTP
The general command format of the Internet protocol based on TCP/IP is implemented through the request/response method, and all text information is used, so
It's a little easier to deal with. SMTP is the abbreviation of Simple Mail Transfer Protocol, which enables the client to send emails to the server. So
The command mentioned below refers to the client sending a request instruction to the server, and the response refers to the information returned by the server to the client.

SMTP is divided into two parts: command header and message body. The command header mainly completes the connection between the client and the server, verification, etc. The whole process consists of multiple lives
Order composition. After each command is sent to the server, the server will give response information, usually a 3-digit response code and response text. Different servers
The response code returned by the server is protocol-compliant, but the response body does not. There is a carriage return character at the end of each command and response, so
Use fputs() and fgets() to process commands and responses. SMTP command and response messages are single lines. Is the information body timid?
In the body part of the text, the last closing line should be ended with a separate "."

Some commonly used SMTP commands on the client are:

HELO hostname: Greet the server and tell the client the machine name used. You can fill it in casually
MAIL FROM: sender_id: Tell the server the address of the sender
RCPT TO: receiver_id: Tell the server the address of the recipient
DATA: The content of the letter begins to be transmitted below, and it must end with a special line containing only .
RESET: Cancel the previous command and start over
VERIFY userid: Verify whether the account exists (this command is optional and may not be supported by the server)
QUIT: Quit the connection, end
The response information returned by the server is (the format is: response code + space + explanation):

220 Service ready (this information will be returned when the socket connection is successful)
221 Processing
250 The request email action is correct and completed (this information will be returned if the HELO, MAIL FROM, RCPT TO, QUIT command is executed successfully)
354 starts sending data and ends with . (This information will be returned if the DATA command is successfully executed, and the client should send the information)
500 Syntax error, command not recognized
550 Command cannot be executed, the email is invalid
552 Interrupt handling: User exceeded file space
The following is a simple command header (this is done after opening the socket), which is the test result of sending an email to stmp.263.net:

HELO limodou
250 smtp.263.net
MAIL FROM: chatme@263.net
250 Ok
RCPT TO: chatme@263.net
250 Ok
DATA
354 End data with .
To: chatme@263.net
From: chatme@263.net
Subject: test
From: chatme@263.net
test
.
QUIT
250 Ok: queued as C46411C5097E0

This is some simple knowledge about SMTP. Related content can be found in RFC.

RFC 821 defines related commands for receiving/sending emails.
RFC 822 specifies the format of email content.
RFC 2045-2048 specifies the format for multimedia email content,
RFC 1113, 1422-1424 discusses how to improve the confidentiality of email.

Implementation of send_mail class
Now let’s introduce the sending email class I wrote. With the above preparatory knowledge, the following is the implementation.

Member variables of class

var $lastmessage; //Record the last response message returned
var $lastact; //Last action, string form
var $welcome; //Used after HELO to welcome users
var $debug; //Whether to display debugging information
var $smtp; //smtp server
var $port; //smtp port number
var $fp; //socket handle

Among them, $lastmessage and $lastact are used to record the last response information and the executed command. When an error occurs, the user can use it
them. For testing needs, I also defined the $debug variable. When its value is true, some execution information will be displayed during the running process, otherwise nothing
any output. $fp is used to save the opened socket handle.

Construction of class


-------------------------------------------------- -------------------------------
function send_mail($smtp, $welcome="", $debug=false)
{
if(empty($smtp)) die("SMTP cannt be NULL!");
$this->smtp=$smtp;
if(empty($welcome))
{
$this->welcome=gethostbyaddr("localhost");
}
else
$this->welcome=$welcome;
$this->debug=$debug;
$this->lastmessage="";
$this->lastact="";
$this->port="25";
}
-------------------------------------------------- -------------------------------
This constructor mainly completes the determination and setting of some initial values. $welcome is used in the HELO directive to tell the server the user's name.
The HELO instruction requires a machine name, but it can be used without it. If the user does not provide $welcome, the local machine name is automatically searched.

Show debugging information

-------------------------------------------------- ----------------------------------
1 function show_debug($message, $inout)
2 {
3 if ($this->debug)
4 {
5 if($inout=="in") //Response information
6 {
7 $m=<< ;
8}
9 else
10
$m=>> ;
11 if(!ereg(" $", $message))
12 $message .= "
";
13 $message=nl2br($message);
14 echo "${m}${message}";
15 }
16 }
-------------------------------------------------- ----------------------------------

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486554.htmlTechArticleAmong the several PHP homepage spaces that the author has applied for, there are not many that can provide the mail function. They always call After finishing the mail() function, there is nothing further. But the role of email in online life...
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