Accessing POP Emails in PHP using imap library

With the use of the IMAP library you will be able to access pop3 email inboxes.

The following will access a pop3 inbox, get count of emails and print out basic details about the emails.


$user = 'someuser@somedomain.com';
$pass = 'somepassword';
$host = '255.255.0.1';

// Connect to the pop3 email inbox belonging to $user
// If you need SSL remove the novalidate-cert section
$con = imap_open("{$host/pop3/novalidate-cert}INBOX", $user, $pass);

$MC = imap_check($con); 

// Get the number of emails in inbox
$range = "1:".$MC->Nmsgs; 

// Retrieve the email details of all emails from inbox
$response = imap_fetch_overview($con,$range); 

// displays basic email info such as from, to, date, subject etc...
foreach ($response as $msg) {

	echo '<pre>';
	var_dump($msg);
	echo '</pre><br>-----------------------------------------------------<br>';
}

Getting email headers

This will retrieve whats in the email headers and print them out.


$user = 'someuser@somedomain.com';
$pass = 'somepassword';
$host = '255.255.0.1';

// Connect to the pop3 email inbox belonging to $user
// If you need SSL remove the novalidate-cert section
$con = imap_open("{$host/pop3/novalidate-cert}INBOX", $user, $pass);

$MC = imap_check($con); 

// Retrieve the email header data
// message count $i starts from 1
for ($i=1; $i<=$MC->Nmsgs; $i++) {
    $header = imap_header($con, $i);
   // imap_fetachheader() retrieves the raw header 
   //$header = imap_fetchheader($con, $i);
    echo '<pre>';
    var_dump($header);
    echo '</pre><br>-----------------------------------------------------<br>';
}

Deleting emails from mailbox

When deleting you must first mark individual email to be deleted. At the end of your processing you execute imap_expunge() to actually remove the marked emails from the mailbox.


$con = imap_open("{$host/pop3/novalidate-cert}INBOX", $user, $pass);

$MC = imap_check($con);

$range = "1:".$MC->Nmsgs; 

// Retrieve the email details of all emails from inbox
$response = imap_fetch_overview($con,$range); 

foreach ($response as $msg) {
    .....
    // Mark email to be deleted. Should use uid to delete. 
   // Gmail only allows deleting emails with uid.
   imap_delete($con, $msg->uid, FT_UID);
}

// Delete the emails that are marked
imap_expunge($con);

Leave a comment

0 Comments.