MexiCode Ideas en codigo

Read IMAP Emails with PHP

Posted on February 20, 2010

Well, at work we are all about google app for your domain, we use it for virtually anything. So, we started a new project, in which we had to read emails from our web application, and I remembered reading something about php_imap somewhere, so I decided to check it out.

Lucky as I always am, our hosting provider already had this module installed and working, so I didn“t have to go thru any extra steps, just right on programming.

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
// Open pop mailbox
if (!$mbox = imap_open ("{imap.gmail.com:993/ssl/novalidate-cert}", "mail@googledomain.com", "password"))
{
    die ('Cannot connect/check pop mail! Exiting');
}
 
if ($hdr = imap_check($mbox))
{
    $msgCount = $hdr->Nmsgs;
}
else
{
    die("Failed to get mail");
}
 
//Read $msgCount from INBOX
$MN = $msgCount;
$emails = imap_fetch_overview($mbox,"1:$MN",0);
 
//print email information and delete each email
foreach($emails as $email)
{
    echo "<pre>";
    echo "TO : {$email->to}<br />";
    $file = extract_attachments($mbox, $email->msgno);
    print_r($file);
    echo "</pre>";
    imap_delete($mbox, $email->msgno);
}
 
//delete emails marked for deletion and close connection
imap_expunge($mbox);
imap_close($mbox);

Well, thats shows how to connect to a google domain. I'll talk about the "extract_attachments" function in another post, I'm pretty tired right now.

You should really check the PHP imap function list. There is some really cool stuff going on in there.

NOTE TO SELF the novalidate-cert bit on the connection string to the imap inbox, saves you from quite a few headaches

Tagged as: , No Comments