Get emails from mailbox with PHP
With PHP it is very easy to send emails, as I have shown you in a recent article. With PHP you can do event more. It has functions to read mails directly from your mailbox. So it is possible to create automatic systems which are able to read messages from your inbox and react on them. You can for example start a process by sending a start command to your mailbox.
Create a connection to your mailbox
The following code shows how to connect with an existing IMAP mailbox:
$mbox = imap_open($server, $adresse, $password, OP_READONLY);
For our connection we need a function called imap_open. This function needs some params which are:
the first param is the server to which we want to establish the connection. This server hosts the IMAP mailbox. We need a domain name and a port. For IMAP the standard port is 143. It is possible that you need a different port. If the connection is SSL save than you may need 993.
next param is your username or account name. Normally this is your mail address that you use to get your mails.
you mailbox password.
- optional params
you can use some optional params here. For my example we only want to read mails so we set read only.
The result is a IMAP stream for your mailbox or false if something went wrong.
Get header and body of mails
You can use the IMAP steam to get header and body informations of all mails in mailbox. For this we can use PHP functions imap_headers and imap_fetchbody. This works for text mails and also HTML mails.
$headers = imap_headers($mbox);
$text = imap_fetchbody($mbox, $no, 1);
for($i = 0; $i < count($headers); ++$i)
echo "Header: ".$headers[$i]."<br>";
echo "Body: ".imap_fetchbody($mbox, $i+1, 1)."<br>";