Author: Manuel Lemos
Viewers: 3,957
Last month viewers: 1,192
Package: POP3 e-mail client
Using a POP3 or IMAP mailbox is a very reliable and platform independent solution.
This article explains how to handle incoming e-mail using a POP3 client script and compares it with other solutions that depend on the local mail server type.
Contents
How Can PHP Read Mail
Starting a Script on Message Arrival to have PHP Process Incoming Email
PHP Mail Client for Accessing Received Messages via POP3 or IMAP
Parsing and processing received messages
PHP HTML Email Processing
Immediate processing versus POP3 or IMAP access to messages
How Can PHP Read Mail
Some PHP applications need to handle incoming e-mail sent to a certain address and process the messages in a way that suits the application needs.
For instance, if you want to develop a simple CRM application (Customer Relationship Management), usually it needs to receive the messages sent by the customers to a given address and process them somehow.
A typical e-mail processing script stores the message details in a database, so the messages can be handled later by a customer support representative.
PHP can help in this situation by automatically receiving and performing the initial processing of the incoming messages.
Starting a Script on Message Arrival to have PHP Process Incoming Email
One way to process the incoming messages is to configure the local mail server to start a PHP script when a message arrives on a given mailbox.
To achieve this, you need to learn specific details of how to configure your mail server because each mail server works in a different way.
For instance, if you use qmail mail server, you need to setup a .qmail file associated to the e-mail address that you want to handle. The .qmail file must contain the command that will be executed to start the PHP script that will handle the incoming messages.
For instance, if PHP CLI (Command Line Interface) version path is /usr/bin/php , and the path of the PHP script that will process the messages is /home/crm/bin/request.php, the .qmail file must have this line:
/usr/bin/php /home/crm/bin/request.phpThe incoming message data is passed to PHP via the standard input. Therefore, you can read the message as if it was a file with name php://stdin , for instance like this:
$message = file_get_contents( 'php://stdin' );
PHP Mail Client for Accessing Received Messages via POP3 or IMAP
An alternative solution to process received e-mail messages using PHP is to associate the incoming addresses to mailboxes accessible using POP3 or IMAP client scripts.
In this case, the messages are received and stored by the mail server, so they can be processed later by applications.
PHP scripts can use existing POP3 or IMAP client classes or extensions to regularly poll the mail server and retrieve the messages to perform the necessary processing tasks.
To perform this periodic poll, you can use the PHP CLI version command to start a PHP script by adding a task to cron on Linux and other Unix like systems, or the task scheduler on Windows.
Depending on how important the incoming messages may be, you may adjust the frequency of execution of the mailbox polling script.
For instance, if PHP CLI version command path is /usr/bin/php , and the path of the script that will process the messages every 5 minutes is /home/crm/bin/request.php, you need to add a cron task by adding a line like this to the crontab:
5 * * * * /usr/bin/php /home/crm/bin/request.phpPHP has the IMAP extension that can access mailboxes either via POP3 or IMAP protocol. However, this extension is not always available in all PHP installations.
Alternatively, this POP3 class can be always used regardless if the IMAP extension available.
The POP3 class comes with a stream handler that allows you to retrieve files from a mailbox, as if the messages were real files. For instance, you can re retrieve the first message from the mailbox like this:
stream_wrapper_register( 'pop3', 'pop3_stream');"user" is the user name of the mailbox account and "password" is the respective password. "pop.mailserver.com" is the mail server host address.
$message = file_get_contents( 'pop3://user:password@pop.mailserver.com/1' );
If you want to process the message and delete it later, which usually you have to do, you need to implement a little more complicated procedure demonstrated by the following code sample. This assures that the messages are listed, retrieved and deleted safely within the same POP3 connection:
/* Set connection options */
$pop3 = new pop3_class;
$pop3->hostname = "pop.mailserver.com";
$pop3->port = 110;
$user = "mailbox_account";
$password = "mailbox_password";
$apop = 0;
/* Connect to the server */
if(($error = $pop3->Open())=="")
{
/* Authenticate */
if(($error = $pop3->Login($user, $password, $apop))=="")
{
/* Setup a file name of a message to be retrieved
* on an already opened POP3 connection */
$pop3->GetConnectionName($connection_name);
$message=1;
$message_file='pop3://'. $connection_name. '/'. $message;
/* Do your message processing here */
$message = file_get_contents($message_file);
/* If all goes well, delete the processed message */
$pop3->DeleteMessage($message);
}
/* Close the connection before you exit */
$pop3->Close();
}
Parsing and processing received messages
E-mail messages may have a complicated structure that it is not easy to parse. This is especially true when you need to extract complex details from the messages like encoded subjects or sender names and addresses, extracting attached files, handle messages with alternative text or HTML parts, embedded images or CSS, etc..
The best solution for handling the complexity of parsing e-mail problems is to use existing e-mail parsing components, like for instance the MIME parser class. It is ready to parse messages by passing it the message file names.
The PHP Email MIME parser class comes with plenty of examples and documentation that you can read to easily learn how to use it to parse the messages that your application needs to handle.
PHP HTML Email Processing
One of the most common uses of the PHP MIME parser with the POP3 e-mail client class is to extract the HTML part of messages, so they can be displayed to the users on Web pages.
Assuming that you got the whole contents of the message into the $message variable, you can extract the HTML from a message using code similar to the following.
Keep in mind that the HTML sent in a message may contain malicious JavaScript code that can be used to steal cookies and other security problems.
It is safer that along this code you also use another package to safely parse and filter insecure HTML code before you display it to your site users. Read this other article to learn how to process and display HTML securely when it comes from unsafe sources like for instance email messages.
// Parse message data $mime=new mime_parser_class; $parameters=array( 'Data'=>$message, ); if(!$mime->Decode($parameters, $decoded)) { // Process parsing error } else { // Analyse the parser results to determine what kind of message is this if($mime->Analyze($decoded[0], $results)) { // Is this a message of HTML type? if($results["Type"] === "html") { // Output message HTML body echo $results["Data"]; } } else echo 'MIME message analyse error: '.$mime->error."\n"; }
Immediate processing versus POP3 or IMAP access to messages
Before you decide which method is the best, you need to understand that each method has advantages and disadvantages. Let me give an overview of the most important details.
Immediate processing of messages passed by the mail server
a) The messages are processed immediately as they are received by the mail server.
b) If your message processing script fails for some reason, you loose the messages. Therefore it is not recommended for applications on which the received messages are critical.
c) The mail processing script must run on the same machine as the mail server.
d) Setting up a mail processing script is a task that depends on the type of mail server.
Processing messages polling a POP3 or IMAP server
a) The mail server must be polled regularly, so there may be delays in processing messages if the polling is not frequent enough.
b) If message processing takes too long, you need to be careful to not start processing one message before the previous message was processed. POP3 servers lock mailboxes while a connection to the server is not closed.
c) The mail processing script may poll a server that is running on a different machine.
d) Accessing messages in mailbox via POP3 or IMAP does not depend on the platform PHP is running on.
Download the POP3 Processing Email PHP Code
You may find more information on how to access and process messages dropped in POP3 mailboxes by looking at the example scripts and documentation available with the described classes.You can download the PHP POP3 class ZIP archive or install it using the composer tool with the instructions from the install page.
If you have more questions feel free to post a comment to this article.
You need to be a registered user or login to post a comment
Login Immediately with your account on:
Comments:
33. abc - Chaitu Patil (2018-12-04 13:19)
xyz... - 0 replies
Read the whole comment and replies
32. forward message or save it in the DB - Diana Parvanova (2017-07-20 21:58)
forward message or save it in the DB... - 2 replies
Read the whole comment and replies
28. Access email with Message-ID - jay (2015-10-28 12:51)
header Message-ID specific email... - 1 reply
Read the whole comment and replies
26. Error: 3 POP3 server greeting was not found - Naresh Kumar (2014-12-17 10:02)
Getting Error : 3 POP3 server greeting was not found... - 1 reply
Read the whole comment and replies
24. Getting the body of a message - James Crawford (2014-08-23 11:07)
how to to get the body of a message... - 2 replies
Read the whole comment and replies
23. basics of getting emails from mailserver - creet dree (2014-05-26 21:09)
beginning email retrieval... - 1 reply
Read the whole comment and replies
21. applications of your pop3 class - creet dree (2014-05-20 22:26)
where and how to apply it?... - 9 replies
Read the whole comment and replies
22. Great example, need a little help - Drew Riley (2014-05-17 18:06)
how can i rename the attachments based on email headers?... - 3 replies
Read the whole comment and replies
18. step by step guide - creet dree (2014-03-31 22:08)
using php to get emails from server on ubuntu 10.04... - 5 replies
Read the whole comment and replies
20. rfc822_addresses.php - creet dree (2014-03-31 09:24)
rfc822_addresses.php... - 1 reply
Read the whole comment and replies