Skip to content
Chris A edited this page Dec 25, 2022 · 11 revisions

Example #1

$mailbox = new PhpImap\Mailbox(
	'{imap.gmail.com:993/ssl/novalidate-cert/imap}', 
	'example@gmail.com', 
	'password', 
	false // when $attachmentsDir is false we don't save attachments
);

// get the list of folders/mailboxes
$folders = $mailbox->getMailboxes('*'); 

// loop through mailboxs
foreach($folders as $folder) {

	// switch to particular mailbox
	$mailbox->switchMailbox($folder['fullpath']); 
	
	// search in particular mailbox
	$mails_ids[$folder['fullpath']] = $mailbox->searchMailbox('SINCE "24 Jan 2018" BEFORE "25 Jan 2018"');
}

var_dump($mails_ids);

Example #2

Method imap() allow to call any imap function in a context of the the instance.

$mailbox = new PhpImap\Mailbox(
	'{outlook.office365.com:993/imap/ssl}', 
	'example@gmail.com', 
	'password', 
	__DIR__,
	'US-ASCII' // force charset different from UTF-8
);

// Calls imap_check(); 
// http://php.net/manual/en/function.imap-check.php
$info = $mailbox->checkMailbox();

// Show current time for the mailbox
$current_server_time = isset($info->Date) && $info->Date ? date('Y-m-d H:i:s', strtotime($info->Date)) : 'unknown';

echo $current_server_time;

Example #3

<?php
namespace PhpImap;
require 'src/PhpImap/__autoload.php';
?>
<!DOCTYPE html>
<html>
<head>
<style>
    div#wrap {width:860px; margin:20px auto;}
</style>
</head>
<body>
<div id="wrap">
<?php

// Configuration for the Mailbox class
$hoststring = '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX';
$username   = 'youraccount@gmail.com';
$password   = 'gmailpassword';
$attachdir  = 'attachments';

// Construct the $mailbox handle
$mailbox = new Mailbox($hoststring, $username, $password, $attachdir);

// Get INBOX emails after date 2017-01-01
$mailsIds = $mailbox->searchMailbox('SINCE "20170101"');
if(!$mailsIds) exit('Mailbox is empty');

// Show the total number of emails loaded
echo 'n= '.count($mailsIds).'<br>';

// Put the latest email on top of listing
rsort($mailsIds);

// Get the last 15 emails only
array_splice($mailsIds, 15);

// Loop through emails one by one
foreach($mailsIds as $num) {
    
    // Show header with subject and data on this email
    $head = $mailbox->getMailHeader($num);
    echo '<div style="text-align:center"><b>';
    echo $head->subject.'</b>&nbsp;&nbsp;(';
    if     (isset($head->fromName))    echo 'by '.$head->fromName.' on ';
    elseif (isset($head->fromAddress)) echo 'by '.$head->fromAddress.' on ';
    echo $head->date.')';
    echo '</div>';
    
    // Show the main body message text
    // Do not mark email as seen
    $markAsSeen = false;
    $mail = $mailbox->getMail($num, $markAsSeen);
    if ($mail->textHtml)
        echo $mail->textHtml;
    else
        echo $mail->textPlain;
    echo '<br><br>';
    
    // Load eventual attachment into attachments directory
    $mail->getAttachments();

}

$mailbox->disconnect();
?>
</div>
</body>
</html>
Clone this wiki locally