Skip to content
Edvinas Selskas edited this page Dec 9, 2020 · 8 revisions

Examples for PhpImap\Mailbox()

The most important code is the one, which creates a new instance of PhpImap\Mailbox:

$mailbox = new PhpImap\Mailbox(
	$imapPath, // IMAP server and mailbox folder
	$login, // Username for the before configured mailbox
	$password, // Password for the before configured username
	$attachmentsDir = null, // Directory, where attachments will be saved (optional)
	$serverEncoding = 'UTF-8' // Server encoding (optional)
);

As you can see, the last two parameters have a default value, so these are optional and not required. The $serverEncoding is by default set to UTF-8. You may want to change this directly in the above code or later with $mailbox->setServerEncoding('US-ASCII').

Example 1) SSL secured IMAP without saving attachments automatically

This example will connect to the server imap.gmail.com on port 993 via the IMAP protocol and enabled SSL and opens the mailbox folder INBOX (which is by the way the default).

You can switch the mailbox in your code later at any time using the function $mailbox->switchMailbox($folderPath).

some@gmail.com will authenticate against this IMAP server in order to fetch emails from the INBOX.

$mailbox = new PhpImap\Mailbox(
	'{imap.gmail.com:993/imap/ssl}INBOX', // IMAP server incl. flags and optional mailbox folder
	'some@gmail.com', // Username for the before configured mailbox
	'*********' // Password for the before configured username
);

The full supported list of flags for the IMAP server can be found at PHP.net - imap_open. See parameter "mailbox".

Example 2) Automatically save email attachments

As we have defined the fourth parameter to __DIR__ in this example, the library will automatically download and save all attachments of the email(s) to the specified directory.

For your information: __DIR__ is a magic constant, which simply points to the same directory as where the PHP script is located.

The specified directory must be a valid and already existing directory. You can for example use /var/www/example.com/mails/, as long as this directory exists and your application (usually the web server) has permissions to write files there.

$mailbox = new PhpImap\Mailbox(
	'{imap.gmail.com:993/imap/ssl}INBOX', // IMAP server and mailbox folder
	'some@gmail.com', // Username for the before configured mailbox
	'*********', // Password for the before configured username
	__DIR__ // Directory, where attachments will be saved (optional)
);

Example 3) Change default encoding

By default, the server encoding is set to UTF-8. You may want or need to change this to something different. In this example, we will change it to 'US-ASCII':

$mailbox = new PhpImap\Mailbox(
	'{imap.gmail.com:993/imap/ssl}INBOX', // IMAP server and mailbox folder
	'some@gmail.com', // Username for the before configured mailbox
	'*********', // Password for the before configured username
	__DIR__, // Directory, where attachments will be saved (optional)
	'US-ASCII' // Server encoding (optional)
);

Disable processing of attachments to boost performance

By default, all fetched emails will be parsed to extract the attachments. When you don't need those attachments it makes sense to skip this task in order to significantly improve the performance:

$mailbox->setAttachmentsIgnore(true);

Show, if email has attachments or not

Using the method hasAttachments() you are able to see, if your current email has attachments or not, even when you have disabled the processing of attachments:

// Get any message
// In this example, we will just take the first one
$mail = $mailbox->getMail($mailsIds[0]);

// Show, if $mail has one or more attachments
echo "\nMail has attachments? ";
if($mail->hasAttachments()) {
	echo "Yes\n";
} else {
	echo "No\n";
}

Note: The number of attachments is only available, when you process the attachments. Otherwise, getAttachments() will be empty.

Full Example

Next, you will see a sample code how you can use this library.

For further examples, you may take a look at the other wiki page: Examples of usage

// Connect to server imap.gmail.com via SSL on port 993 and open the 'INBOX' folder
// Authenticate with the username / email address 'some@gmail.com'
// Save attachments to the directory '__DIR__'
// Set server encoding to 'US-ASCII'
$mailbox = new PhpImap\Mailbox(
	'{imap.gmail.com:993/imap/ssl}INBOX', // IMAP server and mailbox folder
	'some@gmail.com', // Username for the before configured mailbox
	'*********', // Password for the before configured username
	__DIR__, // Directory, where attachments will be saved (optional)
	'US-ASCII' // Server encoding (optional)
);

try {
	// Search in mailbox folder for specific emails
	// PHP.net imap_search criteria: http://php.net/manual/en/function.imap-search.php
	// Here, we search for "all" emails
	$mails_ids = $mailbox->searchMailbox('ALL');
} catch(PhpImap\Exceptions\ConnectionException $ex) {
	echo "IMAP connection failed: " . $ex;
	die();
}

// Change default path delimiter '.' to '/'
$mailbox->setPathDelimiter('/');

// Switch server encoding
$mailbox->setServerEncoding('UTF-8');

// Change attachments directory
// Useful, when you did not set it at the beginning or
// when you need a different folder for eg. each email sender
$mailbox->setAttachmentsDir('/var/www/example.com/ticket-system/imap/attachments');

// Disable processing of attachments, if you do not require the attachments
// This significantly improves the performance
$mailbox->setAttachmentsIgnore(true);

// Loop through all emails
foreach($mails_ids as $mail_id) {
	// Just a comment, to  see, that this is the begin of an email
	echo "+------ P A R S I N G ------+\n";

	// Get mail by $mail_id
	$email = $mailbox->getMail(
		$mail_id, // ID of the email, you want to get
		false // Do NOT mark emails as seen
	);

	echo "from-name: " . (isset($email->fromName)) ? $email->fromName : $email->fromAddress;
	echo "from-email: " . $email->fromAddress;
	echo "to: " . $email->to;
	echo "subject: " . $email->subject;
	echo "message_id: " . $email->messageId;

	echo "mail has attachments? ";
	if($email->hasAttachments()) {
		echo "Yes\n";
	} else {
		echo "No\n";
	}

	if(!empty($email->getAttachments())) {
		echo count($email->getAttachments()) . " attachements";
	}
	if($email->textHtml) {
		echo "Message HTML:\n" . $email->textHtml;
	} else {
		echo "Message Plain:\n" . $email->textPlain;
	}

	if(!empty($email->autoSubmitted)) {
		// Mark email as "read" / "seen"
		$mailbox->markMailAsRead($mail_id);
                echo "+------ IGNORING: Auto-Reply ------+";
	}

	if(!empty($email->precedence)) {
		// Mark email as "read" / "seen"
		$mailbox->markMailAsRead($mail_id);
		echo "+------ IGNORING: Non-Delivery Report/Receipt ------+";
	}
}

// Disconnect from mailbox
$mailbox->disconnect();

A full list of all available functions can be found in the Mailbox class by searching for public function.