Using the Email Forward Robot

There are many options for working with emails. One of the options is to implement the PHP IMAP classes. Doing this lets you create highly custom programs and automation for your business.

Take a look at my email forwarding robot found here:

I made this at work. I needed a way to log into a mailbox and forward all of the emails from customers. There would be some emails in there from the company itself and those could be ignored. I found the EmailReader class somewhere. There are a few other examples out there on how to use it. I wrote the script ’emailForwards.php’ to be used as a cron job.

How to use the Email Robot

Set up your creds

Edit the variables at the top of the file, ’emailForwards.php’. You can make a copy for each email account you want to log into. Input the mailbox credentials, the email address where the forwards are going to, and the ‘from’ and ‘reply-to’ fields to be used in the header of the forward.

Set the script as a cron job

Supposing that you wanted to check your inbox each night at midnight your cron would look like this:

0 0 * * * /path/to/email-forward-robot/emailForwards.php >> /path/to/email-forward-robot/logs/forwardingLog

Looking at the code

Suppose you wanted to log into an outlook account, check how many emails there are, and get one or more.


// login creds
$server = '' ;
$user = '[email protected]' ;
$pass = 'password';
$port = 993;

// init the email reader
$emailReader = new EmailReader($server, $user, $pass, $port);

// get count of messages
$numberOfMessages = $emailReader->getMessageCount();

// get all messages
$messages = []; 
for ($i = 0; $i < $numberOfMessages; $i++) 
    array_push($messages, $emailReader->get($i)); 

The script uses the imap_mail to forward the messages to the admin. This function is part of the PHP standard library. It’s not part of the EmailReader class. At the time I built this script I just needed a working solution. I wasn’t worried about extending other people’s code. My company only ever used this script to check four email accounts. It worked successfully each time.