PHP Read A IMAP Email Inbox

Reading a IMAP email inbox with PHP can be so using this class example.

There are 4 example function to

  • connect to the inbox
  • read the inbox
  • get errors
  • disconnect from the inbox

All you need from the inbox is the:

  • server address
  • inbox username
  • inbox password

All code examples are open source and everyone is welcome to use them.

Example Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class imapManager extends \Core\Controller\Controller
{
    protected $connection;
    protected $mailArray = array();

    public function connect($server, $username, $password)
    {
        $this->connection = imap_open('{'. $server .':143/novalidate-cert}INBOX', $username, $password);
        if ($this->connection === FALSE) {
            return FALSE;
        }
    }

    public function getErrors()
    {
        return imap_errors();
    }

    public function readInbox()
    {
        $msgCount = imap_sort($this->connection, SORTDATE, 1, SE_UID);
        foreach ($msgCount as $msg) {
            $msgno = imap_msgno($this->connection, $msg);
            $header = imap_headerinfo($this->connection, $msgno);
            $this->mailArray[$header->udate] = [imap_body($this->connection, $msgno), $msg];
        }

        return $this->mailArray;
    }

    public function disconnect()
    {
        imap_close($this->connection);
        unset($this->connection);
    }
}

Have a look at some of our other code snippets Click Here