Source for file IMAP.php
Documentation is available at IMAP.php
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Richard York <richy@smilingsouls.net> |
// +----------------------------------------------------------------------+
// {{{ Mail_IMAP::getBody action options
define('MAIL_IMAP_LITERAL', 1 );
define('MAIL_IMAP_LITERAL_DECODE', 2 );
define('MAIL_IMAP_SET_FLAGS', 3 );
define('MAIL_IMAP_CLEAR_FLAGS', 4 );
* Mail_IMAP provides a simplified backend for working with the c-client (IMAP) extension.
* It serves as an OO wrapper for commonly used c-client functions.
* It provides structure and header parsing as well as body retrieval.
* This package requires the c-client extension. To download the latest version of
* the c-client extension goto: http://www.php.net/imap.
* Net_URL (Required if you will be using a URI abstraction to connect.)
* Potential bugs may arise from the detection of certain multipart/* messages.
* Application parses and adjusts for anomalies in multipart/mixed,
* multipart/related and multipart/alternative messages. Bugs may arise from
* untested and unincluded multipart message types, multipart/parallel,
* multipart/report, multipart/signed and multipart/digest. If you happen
* across a problem related to one of the untested message types, please mail a
* copy of the message (if possible) to demo@smilingsouls.net where I may
* analyze the message structure and include it in the class. Be sure to include
* Mail_IMAP (multipart/*) in the subject line so that I know the message isn't
* SPAM and don't delete it.
* Having trouble finding the example files?
* Examples are located in the PEAR install directory under /docs/Mail_IMAP/examples
* Extended documentation available at:
* http://www.spicypeanut.net
* @author Richard York <richy@smilingsouls.net>
* @copyright (c) Copyright 2004, Richard York, All Rights Reserved.
* @example examples/IMAP.inbox.php
* @example examples/IMAP.message.php
* @example examples/IMAP.connection_wizard.php
* Mail_IMAP Connection Wizard
* @example examples/IMAP.connection_wizard_example.php
* Mail_IMAP Connection Wizard
* Contains the imap resource stream.
* Contains information about the current mailbox.
* @var array $mailboxInfo
* (string) contains the various possible data types.
var $_dataTypes = array ('text', 'multipart', 'message', 'application', 'audio', 'image', 'video', 'other');
* (string) Contains the various possible encoding types.
* @var array $_encodingTypes
var $_encodingTypes = array ('7bit', '8bit', 'binary', 'base64', 'quoted-printable', 'other');
// --------------------------ALL MESSAGE PARTS-----------------------------
* (object) Contains the object returned by {@link imap_fetchstructure}.
* (str) Contains all of the part ids for a given message.
* (string) Contains all of the part mime types for a given message.
* (int) Contains the file size in bytes for message parts.
* (str) Contains the original file name for a message part (if any).
* (string) Contains the part disposition inline | attachment.
* @var array $_disposition
* (str) Contains the part encoding.
* (str) Contains the part id for multipart/related (if any).
* (bool) Determines whether the current part has attachments.
* @var array $_hasAttachments
// --------------------------INLINE MESSAGE PARTS-----------------------------
* (str) Inline part MIME type.
* (int) Inline file size of the part in bytes.
* (int) Inline file name of the part, if any.
* (bool) Inline part has attachments?
* @var array $inHasAttach
* (str) Inline CID for multipart/related.
// --------------------------ATTACHMENT MESSAGE PARTS-----------------------------
* (str) Attachment part id.
* (str) Attachment MIME type.
* @var array $attachFtype
* (int) Attachment file size in bytes.
* @var array $attachFsize
* (str) Attachment original file name (if any, if not file name is empty string).
* @var array $attachFname
* (bool) Attachment has attachments?
* @var array $attachHasAttach
// -------------------------- MESSAGE HEADERS -----------------------------
* (str) Contains raw message headers fetched from {@link imap_fetchbody}
* or {@link imap_fetchheader} depending on which message part is being retrieved.
* (array)(mixed) Associative array containing information gathered by {@link imap_headerinfo}
* or {@link imap_rfc822_parse_headers}.
* @var header array $header
* Constructor. Optionally set the IMAP resource stream.
* If IMAP connection arguments are not supplied, returns NULL. Accepts
* a URI abstraction of the standard imap_open connection argument
* (see {@link connect}) or the imap resource indicator.
* @param string $connect (optional) server URL to connect to
* @param int $options (optional) options see imap_open
* @return BOOL|NULL|PEAR_Error
function Mail_IMAP($connection = NULL , $options = NULL )
return PEAR ::raiseError ('Error: Supplied resource is not a valid IMAP stream.');
* Wrapper method for {@link imap_open}. Accepts a URI abstraction in
* the following format: imap://user:pass@mail.example.com:143/INBOX#notls
* instead of the standard connection arguments used in imap_open.
* Replace the protocol with one of pop3|pop3s imap|imaps nntp|nntps.
* Place intial folder in the file path portion, and optionally append
* tls|notls|novalidate-cert in the anchor portion of the URL. A port
* number is optional, however, leaving it off could lead to a serious
* degradation in preformance.
* Examples of a well-formed connection argument:
* For IMAP: imap://user:pass@mail.example.com:143/INBOX
* For IMAP SSL: imaps://user:pass@example.com:993/INBOX
* For POP3: pop3://user:pass@mail.example.com:110/INBOX
* For POP3 SSL: pop3s://user:pass@mail.example.com:993/INBOX
* For NNTP: nntp://user:pass@mail.example.com:119/comp.test
* For 'notls' OR 'novalidate-cert' append to the URL as an anchor.
* For 'tls' use secure protocol and add the 'tls' option to the anchor.
* For notls: imap://user:pass@mail.example.com:143/INBOX#notls
* For tls: imaps://user:pass@mail.example.com:143/INBOX#tls
* tls no-validate: imaps://user:pass@mail.example.com:143/INBOX#tls/novalidate-cert
* ssl no-validate: imaps://user:pass@mail.example.com:143/INBOX#novalidate-cert
* If the username is an email address or contains invalid URL characters,
* urlencode the username portion of the string before passing it.
* Use the IMAP.connection_wizard_example.php file to automatically detect
* the correct URI to pass to this function. This file is located in the
* @param string $connect server URL
* @param int (optional) options
* @return PEAR_Error|TRUE
function connect($connect, $options = NULL )
require_once 'Net/URL.php';
$url = & new Net_URL ($connect);
$connect = '{'. $url->host;
if (!empty ($url->port )) {
$connect .= ':'. $url->port;
$secure = ('tls' == substr($url->anchor , 0 , 3 ))? '' : '/ssl';
$connect .= ('s' == (substr($url->protocol , -1 )))? '/'. substr($url->protocol , 0 , 4 ). $secure : '/'. $url->protocol;
if (!empty ($url->anchor )) {
$connect .= '/'. $url->anchor;
// Trim off the leading slash '/'
if (!empty ($url->path )) {
$connect .= substr($url->path , 1 , (strlen($url->path ) - 1 ));
return (FALSE === ($this->mailbox = @imap_open ($connect, urldecode($url->user ), $url->pass )))? PEAR ::raiseError ('Mail_IMAP::connect, unable to build a connection to the specified mail server.') : TRUE;
return (FALSE === ($this->mailbox = @imap_open ($connect, urldecode($url->user ), $url->pass , $options)))? PEAR ::raiseError ('Mail_IMAP::connect, unable to build a connection to the specified mail server.') : TRUE;
* Wrapper method for {@link imap_close}. Close the IMAP resource stream.
* @param int $options (optional) sets the second argument of imap_close
* @return PEAR_Error|TRUE
function close($options = NULL )
return (@imap_close ($this->mailbox))? TRUE : PEAR ::raiseError ('Mail_IMAP::close, unable to close the connection to the mail server.');
return (@imap_close ($this->mailbox, $options))? TRUE : PEAR ::raiseError ('Mail_IMAP::close, unable to close the connection to the mail server.');
* Wrapper method for {@link imap_num_msg}. Calling on this function will reset the IMAP error
* stack (if mailbox is empty). {@link imap_errors} is called to supress a NOTICE level error,
* mailbox is empty, which isn't an error state. For debugging, comment out the call to
* @return int mailbox message count
if (!$message_count = @imap_num_msg ($this->mailbox)) {
$errors = imap_errors (); // Gets rid of the annoying mailbox is empty error!
* Gather message information returned by {@link imap_fetchstructure} and recursively iterate
* through each parts array. Concatenate part numbers in the following format `1.1`
* each part id is separated by a period, each referring to a part or subpart of a
* multipart message. Create part numbers as such that they are compatible with
* {@link imap_fetchbody}.
* @param int &$mid message id
* @param array $sub_part recursive
* @param string $sub_pid recursive parent part id
* @param int $n recursive counter
* @param bool $is_sub_part recursive
* @param bool $skip_part recursive
* @see imap_fetchstructure
function _declareParts (&$mid, $sub_part = NULL , $sub_pid = NULL , $n = 0 , $is_sub_part = FALSE , $skip_part = FALSE )
$this->_structure[$mid] = imap_fetchstructure ($this->mailbox, $mid);
if (isset ($this->_structure[$mid]->parts ) || is_array($sub_part)) {
if ($is_sub_part == FALSE ) {
$parts = $this->_structure[$mid]->parts;
for ($p = 0 , $i = 1; $p < count($parts); $n++ , $p++ , $i++ ) {
// subsequent multipart/alternative if this part is message/rfc822
// Have noticed the existence of serveral other multipart/* types of messages
// but have yet had the opportunity to test on those.
$ftype = (empty ($parts[$p]->type ))? $this->_dataTypes[0 ]. '/'. strtolower($parts[$p]->subtype ) : $this->_dataTypes[$parts[$p]->type ]. '/'. strtolower($parts[$p]->subtype );
$skip_next = ($ftype == 'message/rfc822')? TRUE : FALSE;
if ($ftype == 'multipart/mixed' || $skip_part == TRUE && $ftype == 'multipart/alternative' || $ftype == 'multipart/related') {
$this->_pid[$mid][$n] = ($is_sub_part == FALSE )? (string) " $i" : (string) " $sub_pid.$i";
$this->_ftype[$mid][$n] = $ftype;
$this->_encoding[$mid][$n] = (empty ($parts[$p]->encoding ))? $this->_encodingTypes[0 ] : $this->_encodingTypes[$parts[$p]->encoding ];
$this->_fsize[$mid][$n] = (!isset ($parts[$p]->bytes ) || empty ($parts[$p]->bytes ))? 0 : $parts[$p]->bytes;
// Force inline disposition if none is present
if ($parts[$p]->ifdisposition == TRUE ) {
$this->_disposition[$mid][$n] = strtolower($parts[$p]->disposition );
if ($parts[$p]->ifdparameters == TRUE ) {
$params = $parts[$p]->dparameters;
foreach ($params as $param) {
if (strtolower($param->attribute ) == 'filename') {
$this->_fname[$mid][$n] = $param->value;
$this->_disposition[$mid][$n] = 'inline';
if ($parts[$p]->ifid == TRUE ) {
$this->inline_id[$mid][$n] = $parts[$p]->id;
if (isset ($parts[$p]->parts ) && is_array($parts[$p]->parts )) {
$this->_hasAttachments[$mid][$n] = TRUE;
$n = Mail_IMAP::_declareParts ($mid, $parts[$p]->parts , $this->_pid[$mid][$n], $n, TRUE , $skip_next);
} else if ($skipped == FALSE ) {
$this->_hasAttachments[$mid][$n] = FALSE;
if ($is_sub_part == TRUE ) {
// $parts is not an array... message is flat
$this->_pid[$mid][0 ] = 1;
if (empty ($this->_structure[$mid]->type )) {
$this->_structure[$mid]->type = (int) 0;
if (isset ($this->_structure[$mid]->subtype )) {
$this->_ftype[$mid][0 ] = $this->_dataTypes[$this->_structure[$mid]->type ]. '/'. strtolower($this->_structure[$mid]->subtype );
if (empty ($this->_structure[$mid]->encoding )) {
$this->_structure[$mid]->encoding = (int) 0;
$this->_encoding[$mid][0 ] = $this->_encodingTypes[$this->_structure[$mid]->encoding ];
if (isset ($this->_structure[$mid]->bytes )) {
$this->_fsize[$mid][0 ] = strtolower($this->_structure[$mid]->bytes );
$this->_disposition[$mid][0 ] = 'inline';
$this->_hasAttachments[$mid][0 ] = FALSE;
* Checks if the part has been parsed, if not calls on _declareParts to
* @param int &$mid message id
function _checkIfParsed (&$mid)
if (!isset ($this->_pid[$mid])) {
* sets up member variables containing inline parts and attachments for a specific part
* in member variable arrays beginning with 'in' and 'attach'.
* If inline parts are present, sets {@link $inPid}, {@link $inFtype}, {@link $inFsize},
* {@link $inHasAttach}, {@link $inInlineId} (if an inline CID is specified).
* If attachments are present, sets, {@link $attachPid}, {@link $attachFsize}, {@link $attachHasAttach},
* {@link $attachFname} (if a filename is present, empty string otherwise).
* Typically the text/html part is displayed by default by a message viewer, this part is
* excluded from the inline member variable arrays thourgh $excludeMime by default. If
* $getInline is TRUE the text/plain alternative part will be returned in the inline array
* and may be included as an attachment. Useful for mail developement/debugging of multipart
* @param int &$mid message id
* @param int &$pid part id
* (optional) values: text/plain|text/html, the part MIME type that will be
* @param bool $getAlternative
* (optional) include the plain text alternative part in the created inline parts
function getParts(&$mid, &$pid, $MIME = 'text/html', $getAlternative = TRUE )
if (count($this->_pid[$mid]) == 1 ) {
// retrieve key for this part, so that the information may be accessed
if (FALSE !== ($i = array_search((string) $pid, $this->_pid[$mid]))) {
Mail_IMAP::_scanMultipart ($mid, $pid, $i, $MIME, 'add', 'top', 2 , $getAlternative);
} else if ($this->_ftype[$mid][$i] == 'message/rfc822') {
Mail_IMAP::_scanMultipart ($mid, $pid, $i, $MIME, 'add', 'all', 1 , $getAlternative);
PEAR ::raiseError ('Mail_IMAP::getParts was unable to retrieve a valid part id from the pid passed.', null , PEAR_ERROR_TRIGGER , E_USER_WARNING , 'mid: '. $mid. ' pid: '. $pid);
function _scanMultipart (&$mid, &$pid, &$i, $MIME, $action = 'add', $lookAt = 'all', $pidAdd = 1 , $getAlternative = TRUE )
// Find subparts, create variables
// Create inline parts first, and attachments second
// Get all top level parts, with the exception of the part currently being viewed
// If top level part contains multipart/alternative go into that subpart to
// retrieve the other inline message part to display
// If this part is message/rfc822 get subparts that begin with this part id
// Skip multipart/alternative message part
// Find the displayable message, get plain/text part if $getInline is TRUE
$MIME = ($excludeMIME == 'text/plain')? 'text/html' : 'text/plain';
} else if ($action == 'get') {
foreach ($this->_pid[$mid] as $p => $id) {
// To look at the next level of nesting one needs to determine at which level
// of nesting the program currently resides, this needs to be independent of the
// part id length, since part ids can get into double digits (let's hope they
// don't get into triple digits!)
// To accomplish this we'll explode the part id on the dot to get a count of the
// nesting, then compare the string with the next level in.
case 'all': $condition = (($nesting == ($this_nesting + 1 )) && $pid == substr($this->_pid[$mid][$p], 0 , $pid_len)); break;
case 'multipart': $condition = (($nesting == ($this_nesting + 1 )) && ($pid == substr($this->_pid[$mid][$p], 0 ))); break;
// To gaurantee a top-level part, detect whether a period appears in the pid string
default: $condition = (!stristr($this->_pid[$mid][$p], '.'));
if ($condition == TRUE ) {
if ($this->_ftype[$mid][$p] == 'multipart/alternative') {
foreach ($this->_pid[$mid] as $mp => $mpid) {
// Part must begin with last matching part id and be two levels in
if (($this->_ftype[$mid][$mp] == $MIME && $getAlternative == TRUE && ($sub_nesting == ($this_nesting + $pidAdd)) && ($pid == substr($this->_pid[$mid][$mp], 0 , strlen($this->_pid[$mid][$p]))))) {
} else if ($action == 'get' && !isset ($this->_fname[$mid][$mp]) && empty ($this->_fname[$mid][$mp])) {
return $this->_pid[$mid][$mp];
} else if ($this->_ftype[$mid][$mp] == 'multipart/alternative' && $action == 'get') {
// Need to match this PID to next level in
$pid = (string) $this->_pid[$mid][$mp];
} else if ($this->_disposition[$mid][$p] == 'inline') {
if (( $action == 'add' &&
$this->_ftype[$mid][$p] != $excludeMIME &&
$pid != $this->_pid[$mid][$p]) ||
$this->_ftype[$mid][$p] == $excludeMIME &&
isset ($this->_fname[$mid][$p]) &&
$pid != $this->_pid[$mid][$p])
} else if ($action == 'get' && $this->_ftype[$mid][$p] == $MIME && !isset ($this->_fname[$mid][$p])) {
return $this->_pid[$mid][$p];
} else if ($action == 'add' && $this->_disposition[$mid][$p] == 'attachment') {
* Destroys variables set by {@link getParts} and _declareParts.
* @param integer &$mid message id
unset ($this->inPid[$mid]);
unset ($this->_structure[$mid]);
unset ($this->_pid[$mid]);
unset ($this->_disposition[$mid]);
unset ($this->_encoding[$mid]);
unset ($this->_ftype[$mid]);
unset ($this->_fsize[$mid]);
unset ($this->_fname[$mid]);
unset ($this->_inlineId[$mid]);
unset ($this->_hasAttachments[$mid]);
* Adds information to the member variable inline parts arrays.
* @param int &$in offset inline counter
* @param int &$mid message id
* @param int &$i offset structure reference counter
function _addInlinePart (&$in, &$mid, &$i)
$this->inFname[$mid][$in] = (isset ($this->_fname[$mid][$i]) && !empty ($this->_fname[$mid][$i]))? $this->_fname[$mid][$i] : '';
$this->inPid[$mid][$in] = $this->_pid[$mid][$i];
$this->inFtype[$mid][$in] = $this->_ftype[$mid][$i];
$this->inFsize[$mid][$in] = $this->_fsize[$mid][$i];
$this->inHasAttach[$mid][$in] = $this->_hasAttachments[$mid][$i];
if (isset ($this->_inlineId[$mid][$i])) {
$this->inInlineId[$mid][$in] = $this->_inlineId[$mid][$i];
* Adds information to the member variable attachment parts arrays.
* @param int &$a offset attachment counter
* @param int &$mid message id
* @param int &$i offset structure reference counter
function _addAttachment (&$a, &$mid, &$i)
if (!isset ($this->_fname[$mid][$i])) {
$this->_fname[$mid][$i] = '';
$this->attachPid[$mid][$a] = $this->_pid[$mid][$i];
$this->attachFtype[$mid][$a] = $this->_ftype[$mid][$i];
$this->attachFsize[$mid][$a] = $this->_fsize[$mid][$i];
$this->attachFname[$mid][$a] = $this->_fname[$mid][$i];
* Returns entire unparsed message body. See {@link imap_body} for options.
* @param int &$mid message id
* @param int $options flags
return ($options == NULL )? imap_body ($this->mailbox, $mid) : imap_body ($this->mailbox, $mid, $options);
* Searches parts array set in Mail_IMAP::_declareParts() for a displayable message.
* If the part id passed is message/rfc822 looks in subparts for a displayable body.
* Attempts to return a text/html inline message part by default. And will
* automatically attempt to find a text/plain part if a text/html part could
* Returns an array containing three associative indices; 'ftype', 'fname' and
* 'message'. 'ftype' contains the MIME type of the message, 'fname', the original
* file name, if any, empty string otherwise. And 'message', which contains the
* message body itself which is returned decoded from base64 or quoted-printable if
* either of those encoding types are specified, returns untouched otherwise.
* Returns FALSE on failure.
* @param int &$mid message id
* @param string $pid part id
* (optional) options for body return. Set to one of the following:
* MAIL_IMAP_BODY (default), if part is message/rfc822 searches subparts for a
* displayable body and returns the body decoded as part of an array.
* MAIL_IMAP_LITERAL, return the message for the specified $pid without searching
* subparts or decoding the message (may return unparsed message) body is returned
* MAIL_IMAP_LITERAL_DECODE, same as MAIL_IMAP_LITERAL, except message decoding is
* attempted from base64 or quoted-printable encoding, returns undecoded string
* (optional) one of text/plain or text/html, allows the specification of the default
* part to return from multipart messages, text/html by default.
* (optional) allows the specification of the forth argument of imap_fetchbody
* @return array|string|FALSE
* @see Mail_IMAP::getParts
function getBody(&$mid, $pid, $action = 0 , $getPart = 'text/html', $options = NULL , $attempt = 1 )
return ($options == NULL )? imap_fetchbody ($this->mailbox, $mid, $pid) : imap_fetchbody ($this->mailbox, $mid, $pid, $options);
if (FALSE !== ($i = array_search((string) $pid, $this->_pid[$mid]))) {
$msg_body = ($options == NULL )? imap_fetchbody ($this->mailbox, $mid, $pid) : imap_fetchbody ($this->mailbox, $mid, $pid, $options);
return Mail_IMAP::_decodeMessage ($msg_body, $this->_encoding[$mid][$i]);
// If this is an attachment, and the part is message/rfc822 update the pid to the subpart
// If this is an attachment, and the part is multipart/alternative update the pid to the subpart
if ($this->_ftype[$mid][$i] == 'message/rfc822' || $this->_ftype[$mid][$i] == 'multipart/alternative') {
$new_pid = ($this->_ftype[$mid][$i] == 'message/rfc822')? Mail_IMAP::_scanMultipart ($mid, $pid, $i, $getPart, 'get', 'all', 1 ) : Mail_IMAP::_scanMultipart ($mid, $pid, $i, $getPart, 'get', 'multipart', 1 );
// if a new pid for text/html couldn't be found, try again, this time look for text/plain
case (!empty ($new_pid)): $pid = $new_pid; break;
case (empty ($new_pid) && $getPart == 'text/html'): return ($attempt == 1 )? Mail_IMAP::getBody($mid, $pid, $action, 'text/plain', $options, 2 ) : FALSE;
case (empty ($new_pid) && $getPart == 'text/plain'): return ($attempt == 1 )? Mail_IMAP::getBody($mid, $pid, $action, 'text/html', $options, 2 ) : FALSE;
// Update the key for the new pid
if (FALSE === ($i = array_search((string) $pid, $this->_pid[$mid]))) {
PEAR ::raiseError ('Mail_IMAP::getBody was unable to find a suitable replacement part ID for: '. $pid. '. Message: '. $mid. ' may be poorly formed or corrupted.', NULL , PEAR_ERROR_TRIGGER , E_USER_WARNING );
$msg_body = ($options == NULL )? imap_fetchbody ($this->mailbox, $mid, $pid) : imap_fetchbody ($this->mailbox, $mid, $pid, $options);
PEAR ::raiseError ('Mail_IMAP::getBody message body was NULL for pid: '. $pid. ', is not a valid part number.', NULL , PEAR_ERROR_TRIGGER , E_USER_NOTICE );
// Because the body returned may not correspond with the original PID, return
// an array which also contains the MIME type and original file name, if any.
$body['message'] = Mail_IMAP::_decodeMessage ($msg_body, $this->_encoding[$mid][$i]);
$body['ftype'] = $this->_ftype[$mid][$i];
$body['fname'] = (isset ($this->_fname[$mid][$i]))? $this->_fname[$mid][$i] : '';
PEAR ::raiseError ('Mail_IMAP::getBody was unable to retrieve message body, invalid part id: '. $pid, NULL , PEAR_ERROR_TRIGGER , E_USER_WARNING );
* Decode a string from quoted-printable or base64 encoding. If
* neither of those encoding types are specified, returns string
* @param string &$body string to decode
* @param string &$encoding encoding to decode from.
function _decodeMessage (&$body, &$encoding)
case 'quoted-printable': return imap_qprint ($body);
case 'base64': return imap_base64 ($body);
* Searches structure defined in Mail_IMAP::_declareParts for the top-level default message.
* Attempts to find a text/html default part, if no text/html part is found,
* automatically attempts to find a text/plain part. Returns the part id for the default
* top level message part on success. Returns FALSE on failure.
* @param int &$mid message id
* (optional) default MIME type to look for, one of text/html or text/plain
function getDefaultPid(&$mid, $getPart = 'text/html', $attempt = 1 )
// Check to see if this part has already been parsed
// Look for a text/html message part
// If no text/html message part was found look for a text/plain message part
$part = ($getPart == 'text/html')? array ('text/html', 'text/plain') : array ('text/plain', 'text/html');
foreach ($part as $mime) {
foreach ($msg_part as $i) {
if ($this->_disposition[$mid][$i] == 'inline' && !stristr($this->_pid[$mid][$i], '.')) {
$ret = $this->_pid[$mid][$i];
// If no text/plain or text/html part was found
// Look for a multipart/alternative part
foreach ($this->_pid[$mid] as $p => $id) {
if (!stristr($this->_pid[$mid][$p], '.') && $this->_ftype[$mid][$p] == 'multipart/alternative') {
foreach ($this->_pid[$mid] as $mp => $mpid) {
if ($this->_ftype[$mid][$mp] == $getPart && $nesting == 2 && $this->_pid[$mid][$p] == substr($this->_pid[$mid][$mp], 0 , 1 )) {
$ret = $this->_pid[$mid][$mp];
// if a text/html part was not found, call on the function again
// and look for text/plain
// if the application was unable to find a text/plain part
return ($ret == FALSE )? 1 : $ret;
* Searches all message parts for the specified MIME type. Use {@link getBody}
* with $action option MAIL_IMAP_LITERAL_DECODE to view MIME type parts retrieved.
* If you need to access the MIME type with filename use normal {@link getBody}
* with no action specified.
* Returns an array of part ids on success.
* Returns FALSE if MIME couldn't be found, or on failure.
* @param int &$mid message id
* @param string $MIME mime type to extract
$rtn[] = $this->_pid[$mid][$i];
foreach ($MIME as $mtype) {
$rtn[] = $this->_pid[$mid][$i];
* Set member variable {@link $rawHeaders} to contain Raw Header information
* for a part. Returns default header part id on success, returns FALSE on failure.
* @param int &$mid message_id
* @param string $pid part id
* @param int $options flags/options for imap_fetchbody
// pid is modified in this function, so don't pass by reference (will create a logic error)
if (FALSE !== ($pid = Mail_IMAP::_defaultHeaderPid ($mid, $pid))) {
$this->rawHeaders[$mid] = ($pid == '0')? imap_fetchheader ($this->mailbox, $mid) : imap_fetchbody ($this->mailbox, $mid, $pid);
$this->rawHeaders[$mid] = ($pid == '0')? imap_fetchheader ($this->mailbox, $mid) : imap_fetchbody ($this->mailbox, $mid, $pid, $options);
PEAR ::raiseError ('Mail_IMAP::getRawHeaders unable to retrieve headers, invalid part id: '. $pid, NULL , PEAR_ERROR_TRIGGER , E_USER_WARNING );
* Set member variable containing header information. Creates an array containing associative indices
* referring to various header information. Use {@link var_dump} or {@link print_r} on the {@link $header}
* member variable to view information gathered by this function.
* @param int &$mid message id
* @param string &$pid part id
* @param int $from_length (optional) from length for imap_headerinfo
* @param int $subject_length (optional) subject length for imap_headerinfo
* @param string $default_host (optional) default host for imap_headerinfo & imap_rfc822_parse_headers
* @param int $options (optional) flags/options for imap_fetchbody
* @see imap_rfc822_parse_headers
function getHeaders(&$mid, &$pid, $from_length = 1024 , $subject_length = 1024 , $default_host = NULL , $options = NULL )
// $default_host contains the host information for addresses where it is not
// present. Specify it or attempt to use SERVER_NAME
if ($default_host == NULL && isset ($_SERVER['SERVER_NAME']) && !empty ($_SERVER['SERVER_NAME'])) {
$default_host = $_SERVER['SERVER_NAME'];
} else if ($default_host == NULL ) {
$default_host = 'UNSPECIFIED-HOST-NAME';
$header_info = ($hpid == '0')? imap_headerinfo ($this->mailbox, $mid, $from_length, $subject_length, $default_host) : imap_rfc822_parse_headers ($this->rawHeaders[$mid], $default_host);
// Since individual member variable creation might create extra overhead,
// and having individual variables referencing this data and the original
// object would be too much as well, we'll just copy the object into an
// associative array, preform clean-up on those elements that require it,
// and destroy the original object after copying.
PEAR ::raiseError ('Mail_IMAP::getHeaders unable to retrieve header object, invalid part id: '. $pid, NULL , PEAR_ERROR_TRIGGER , E_USER_WARNING );
foreach ($headers as $key => $value) {
$this->header[$mid][$key] = $value;
// copy udate or create it from date string.
$this->header[$mid]['udate'] = (isset ($header_info->udate ) && !empty ($header_info->udate ))? $header_info->udate : strtotime($header_info->Date );
for ($i = 0; $i < count($line); $i++ ) {
if (isset ($header_info->$line[$i])) {
Mail_IMAP::_parseHeaderLine ($mid, $header_info->$line[$i], $line[$i]);
// All possible information has been copied, destroy original object
// {{{ _parseHeaderLine()
* Parse header information from the given line and add it to the {@link $header}
* array. This function is only used by {@link getRawHeaders}.
function _parseHeaderLine (&$mid, &$line, $name) {
if (isset ($line) && count($line) >= 1 ) {
foreach ($line as $object) {
if (isset ($object->personal )) {
$this->header[$mid][$name. '_personal'][$i] = $object->personal;
if (isset ($object->mailbox ) && isset ($object->host )) {
$this->header[$mid][$name][$i] = $object->mailbox. '@'. $object->host;
// {{{ _defaultHeaderPid()
* Finds and returns a default part id for headers and matches any sub message part to
* the appropriate headers. Returns FALSE on failure and may return a value that
* evaluates to false, use the '===' operator for testing this function's return value.
* @param int &$mid message id
* @param string $pid part id
function _defaultHeaderPid (&$mid, $pid)
// pid is modified in this function, so don't pass by reference (will create a logic error)
// retrieve key for this part, so that the information may be accessed
if (FALSE !== ($i = array_search((string) $pid, $this->_pid[$mid]))) {
// If this part is message/rfc822 display headers for this part
if ($this->_ftype[$mid][$i] == 'message/rfc822') {
$ret = (string) $pid. '.0';
// Deeper searching may be required, go back to this part's parent.
if (!stristr($pid, '.') || ($this_nesting - 1 ) == 1 ) {
} else if ($this_nesting > 2 ) {
// Look at previous parts until a message/rfc822 part is found.
for ($pos = $this_nesting - 1; $pos > 0; $pos -= 1 ) {
foreach ($this->_pid[$mid] as $p => $aid) {
if ($nesting == $pos && $this->_ftype[$mid][$p] == 'message/rfc822') {
// Break iteration and return!
return (string) $this->_pid[$mid][$p]. '.0';
$ret = ($pid_len == 3 )? (string) '0' : FALSE;
PEAR ::raiseError ('Mail_IMAP::_defaultHeaderPid unable to retrieve headers, invalid part id: '. $pid, NULL , PEAR_ERROR_TRIGGER , E_USER_WARNING );
* Destroys variables set by {@link getHeaders}.
* @param int &$mid message id
* Converts an integer containing the number of bytes in a file to one of Bytes, Kilobytes,
* Megabytes, or Gigabytes, appending the unit of measurement.
case ($bytes < pow(2 ,10 )): return $bytes. ' Bytes';
case ($bytes >= pow(2 ,10 ) && $bytes < pow(2 ,20 )): return round($bytes / pow(2 ,10 ), 0 ). ' KB';
case ($bytes >= pow(2 ,20 ) && $bytes < pow(2 ,30 )): return round($bytes / pow(2 ,20 ), 1 ). ' MB';
case ($bytes > pow(2 ,30 )): return round($bytes / pow(2 ,30 ), 2 ). ' GB';
* Wrapper function for {@link imap_delete}. Sets the marked for deletion flag. Note: POP3
* mailboxes do not remember flag settings between connections, for POP3 mailboxes
* this function should be used in addtion to {@link expunge}.
* @param int &$mid message id
* @return TRUE|PEAR_Error
function delete(&$mid, $separator = "<br />\n")
return (imap_delete ($this->mailbox, $mid))? TRUE : PEAR ::raiseError ('Unable to mark message: '. $mid. ' for deletion.');
if (!imap_delete ($this->mailbox, $id)) {
$stack[] = 'Unable to mark message: '. $id. "for deletion.";
return (isset ($stack) && is_array($stack))? PEAR ::raiseError (implode($separator, $stack)) : TRUE;
* Wrapper function for {@link imap_expunge}. Expunges messages marked for deletion.
* @return TRUE|PEAR_Error
return (imap_expunge ($this->mailbox))? TRUE : PEAR ::raiseError ('Unable to expunge mailbox.');
* Wrapper function for {@link imap_errors}. Implodes the array returned by imap_errors,
* (if any) and returns the error text.
* @param string $seperator Characters to seperate each error message. '<br />\n' by default.
function errors($seperator = "<br />\n")
return (is_array($errors) && !empty ($errors))? implode($seperator, $errors) : FALSE;
* Wrapper function for {@link imap_alerts}. Implodes the array returned by imap_alerts,
* (if any) and returns the text.
* @param string $seperator Characters to seperate each alert message. '<br />\n' by default.
function alerts($seperator = "<br />\n")
return (is_array($alerts) && !empty ($alerts))? implode($seperator, $alerts) : FALSE;
* Retreives information about the current mailbox's quota. Rounds up quota sizes and
* appends the unit of measurment. Returns information in a multi-dimensional associative
* @param string $folder Folder to retrieve quota for.
* @return array|PEAR_Error
* @throws Quota not available on this server. Remedy: none.
* @see imap_get_quotaroot
$quota = @imap_get_quotaroot ($this->mailbox, $folder);
// STORAGE Values are returned in KB
// Convert back to bytes first
// Then round these to the simpliest unit of measurement
return (empty ($quota['STORAGE']['usage']) && empty ($quota['STORAGE']['limit']))? PEAR ::raiseError ('Error: Quota not available for this server.') : $rtn;
* Wrapper function for {@link imap_setflag_full}. Sets various message flags.
* Accepts an array of message ids and an array of flags to be set.
* The flags which you can set are "\\Seen", "\\Answered", "\\Flagged",
* "\\Deleted", and "\\Draft" (as defined by RFC2060).
* Warning: POP3 mailboxes do not remember flag settings from connection to connection.
* @param array $mids Array of message ids to set flags on.
* @param array $flags Array of flags to set on messages.
* @param int $action Flag operation toggle one of MAIL_IMAP_SET_FLAGS (default) or
* (optional) sets the forth argument of {@link imap_setflag_full} or {@imap_clearflag_full}.
* @return BOOL|PEAR_Error
* @throws Message IDs and Flags are to be supplied as arrays. Remedy: place message ids
* @see imap_clearflag_full
function setFlags($mids, $flags, $action = 3 , $options = NULL )
return ($options == NULL )? @imap_setflag_full ($this->mailbox, implode(',', $mids), implode(' ', $flags)) : @imap_setflag_full ($this->mailbox, implode(',', $mids), implode(' ', $flags), $options);
return ($options == NULL )? @imap_clearflag_full ($this->mailbox, implode(',', $mids), implode(' ', $flags)) : @imap_clearflag_full ($this->mailbox, implode(',', $mids), implode(' ', $flags), $options);
return PEAR ::raiseError ('Message IDs and Flags are to be supplied as arrays.');
Documentation generated on Mon, 11 Mar 2019 10:15:02 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|