PHP code example of ssilence / php-imap-client

1. Go to this page and download the library: Download ssilence/php-imap-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ssilence / php-imap-client example snippets






use SSilence\ImapClient\ImapClientException;
use SSilence\ImapClient\ImapConnect;
use SSilence\ImapClient\ImapClient as Imap;

$mailbox = 'my.imapserver.com';
$username = 'username';
$password = 'secret';
$encryption = Imap::ENCRYPT_SSL; // TLS OR NULL accepted

// Open connection
try{
    $imap = new Imap($mailbox, $username, $password, $encryption);
    // You can also check out example-connect.php for more connection options

}catch (ImapClientException $error){
    echo $error->getMessage().PHP_EOL; // You know the rule, no errors in production ...
    die(); // Oh no :( we failed
}

// Get all folders as array of strings
$folders = $imap->getFolders();
foreach($folders as $folder) {
    echo $folder;
}

// Select the folder INBOX
$imap->selectFolder('INBOX');

// Count the messages in current folder
$overallMessages = $imap->countMessages();
$unreadMessages = $imap->countUnreadMessages();

// Fetch all the messages in the current folder
$emails = $imap->getMessages();
var_dump($emails);

// Create a new folder named "archive"
$imap->addFolder('archive');

// Move the first email to our new folder
$imap->moveMessage($emails[0]['uid'], 'archive');

// Delete the second message
$imap->deleteMessage($emails[1]['uid']);


// Encryption
$imap = new ImapClient($mailbox, $username, $password, $encryption);
// No Encryption
$imap = new ImapClient($mailbox, $username, $password);

/* Example 1
 * Example 1 is the advanced default connection method
 */
$imap = new ImapClient([
    'flags' => [
        'service' => ImapConnect::SERVICE_IMAP,
        'encrypt' => ImapConnect::ENCRYPT_SSL,
        /* This NOVALIDATE_CERT is used when the server connecting to the imap
         * servers is not https but the imap is. This ignores the failure.
         */
        'validateCertificates' => ImapConnect::NOVALIDATE_CERT,
    ],
    'mailbox' => [
        'remote_system_name' => 'imap.server.ru',
    ],
    'connect' => [
        'username' => 'user',
        'password' => 'pass'
    ]
]);

/* Example 2
 * Get debug messages
 */
$imap = new ImapClient([
    'flags' => [
        'service' => ImapConnect::SERVICE_IMAP,
        'encrypt' => ImapConnect::ENCRYPT_SSL,
        'validateCertificates' => ImapConnect::VALIDATE_CERT,
        // Turns debug on or off
        'debug' => ImapConnect::DEBUG,
    ],
    'mailbox' => [
        'remote_system_name' => 'imap.server.ru',
        'port' => 123,
    ],
    'connect' => [
        'username' => 'user',
        'password' => 'pass'
    ]
]);

/* Example 3
 * You can also set the config then connects
 */
ImapClient::setConnectAdvanced();
ImapClient::setConnectConfig([
    'flags' => [
        'service' => ImapConnect::SERVICE_POP3,
        'validateCertificates' => ImapConnect::VALIDATE_CERT,
        'debug' => ImapConnect::DEBUG,
    ],
]);
$imap = new ImapClient();

/* Example 5
 * Here you can see all the options
 */
$imap = new ImapClient([
    'flags' => [
        # Service can be ImapConnect::SERVICE_IMAP ,ImapConnect::SERVICE_POP3, ImapConnect::SERVICE_NNTP
        'service' => ImapConnect::SERVICE_IMAP,
        # Encrypt can be ImapConnect::ENCRYPT_SSL, ImapConnect::ENCRYPT_TLS, ImapConnect::ENCRYPT_NOTLS
        'encrypt' => ImapConnect::ENCRYPT_SSL,
        # validateCertificates can be ImapConnect::VALIDATE_CERT or ImapConnect::NOVALIDATE_CERT
        'validateCertificates' => ImapConnect::NOVALIDATE_CERT,
        'secure' => ImapConnect::SECURE, # or null
        'norsh' => ImapConnect::NORSH, # or null
        'readonly' => ImapConnect::READONLY, # or null
        'anonymous' => ImapConnect::ANONYMOUS, # or null
        'debug' => ImapConnect::DEBUG # or null
    ],
    'mailbox' => [
        'remote_system_name' => 'imap.server.ru',
        'port' => null,
        'flags' => null,
        'mailbox_name' => null,
    ],
    'connect' => [
        'mailbox' => null,
        'username' => 'user',
        'password' => 'pass',
        'options' => 0,
        'n_retries' => 0,
        'params' => [],
    ]
]);



$mailbox = 'my.imapserver.com';
$username = 'myuser';
$password = 'secret';
$encryption = Imap::ENCRYPT_SSL; // or ImapClient::ENCRYPT_SSL or ImapClient::ENCRYPT_TLS or null

try{

$imap = new Imap($mailbox, $username, $password, $encryption);
# ... and further code ...

}catch (ImapClientException $error){
    echo $error->getInfo();
};              

$folders = $imap->getFolders();
var_dump($folders);
# and
foreach($folders as $folder) {
    echo $folder;
}
# or 
foreach($folders as $folder => $subFolder) {
    echo $folder.PHP_EOL;
    echo $subFolder.PHP_EOL;
}

$imap->selectFolder("Inbox");

$overallMessages = $imap->countMessages();
$unreadMessages = $imap->countUnreadMessages();

$imap->getBriefInfoMessages()

$imap->getMessage(82)

$imap->saveAttachments();

$imap->saveAttachments(['dir'=>'dir/to/save']);

$message = $imap->getMessage(82);
$imap->saveAttachments(['dir' => "your/path/", 'incomingMessage' => $message]);

$imap->saveAttachmetsMessagesBySubject('Special text', 'path/to/save/attach');

var_dump(getHeaderInfo(1));

$imap->getUnreadMessages()

$emails = $imap->getMessages();

foreach($emails as $email){
    echo $email->header->subject.PHP_EOL;
    echo $email->message->plain.PHP_EOL;
};

$imap->addFolder('archive');

$imap->moveMessage($emails[0]['id'], 'archive');

$imap->deleteMessage($emails[1]['id']);

// Note: for slower web servers will less ram use saveEmailSafe()
$imap->saveEmail('archive/users/johndoe/email_1.eml', 1);

$imap->sendMail();

$imap = new ImapClient([
    'flags' => [
        'service' => ImapConnect::SERVICE_IMAP, # ImapConnect::SERVICE_IMAP ,ImapConnect::SERVICE_POP3, ImapConnect::SERVICE_NNTP
        'encrypt' => ImapConnect::ENCRYPT_SSL, # ImapConnect::ENCRYPT_SSL, ImapConnect::ENCRYPT_TLS, ImapConnect::ENCRYPT_NOTLS
        'validateCertificates' => ImapConnect::NOVALIDATE_CERT, # ImapConnect::VALIDATE_CERT, ImapConnect::NOVALIDATE_CERT
        # ... and other
    ],
    'mailbox' => [
        'remote_system_name' => 'imap.server.ru',
        'port' => '431',
        'mailbox_name' => 'INBOX.Send',
        # ... and other
    ],
    'connect' => [
        'username' => 'user',
        'password' => 'pass',
        # ... and other
    ]
]);



namespace program;

mapClientException;
use SSilence\ImapClient\ImapConnect;
use SSilence\ImapClient\ImapClient as Imap;

$mailbox = 'my.imapserver.com';
$username = 'username';
$password = 'secret';
$encryption = Imap::ENCRYPT_SSL;

// Open connection
try{
    $imap = new Imap($mailbox, $username, $password, $encryption);
    // You can also check out example-connect.php for more connection options

}catch (ImapClientException $error){
    echo $error->getMessage().PHP_EOL;
    die(); // Oh no :( we failed
}

// Get all folders as array of strings
$folders = $imap->getFolders();
foreach($folders as $folder) {
    echo $folder;
}

// Select the folder Inbox
$imap->selectFolder('INBOX');

// Count the messages in current folder
$overallMessages = $imap->countMessages();
$unreadMessages = $imap->countUnreadMessages();

// Fetch all the messages in the current folder
$emails = $imap->getMessages();
var_dump($emails);

// Create a new folder named "archive"
$imap->addFolder('archive');

// Move the first email to our new folder
$imap->moveMessage($emails[0]['uid'], 'archive');

// Delete the second message
$imap->deleteMessage($emails[1]['uid']);



namespace program;

t/ImapConnect.php";
use SSilence\ImapClient\ImapConnect;
use SSilence\ImapClient\ImapClient;

$mailbox = 'my.imapserver.com'; // Your iamp server address. If you have a specific port specify it here
$username = 'username'; // Your imap server user name
$password = 'secret'; // Super secret passsword
$encryption = ImapClient::ENCRYPT_TLS; // or ImapClient::ENCRYPT_SSL or ImapClient::ENCRYPT_TLS or null

/*
 * Default connection
 * This is the default way to connect to an IMAP server using this
 */

// Encryption
$imap = new ImapClient($mailbox, $username, $password, $encryption);
// No Encryption
$imap = new ImapClient($mailbox, $username, $password);

/*
 * Advanced connect
 *
 * Options flags same like in ImapConnect::prepareFlags() method
 * Options mailbox same like in ImapConnect::prepareMailbox() method
 * Options connect same like in ImapConnect::connect() method
 */

/* Example 1
 * Example 1 is the advanced default connection method
 */
$imap = new ImapClient([
    'flags' => [
        'service' => ImapConnect::SERVICE_IMAP,
        'encrypt' => ImapConnect::ENCRYPT_SSL,
        /* This NOVALIDATE_CERT is used when the server connecting to the imao
         * servers is not https but the imap is. This ignores the failure.
         */
        'validateCertificates' => ImapConnect::NOVALIDATE_CERT,
    ],
    'mailbox' => [
        'remote_system_name' => 'imap.server.ru',
    ],
    'connect' => [
        'username' => 'user',
        'password' => 'pass'
    ]
]);

/* Example 2
 * Get debug messages
 */
$imap = new ImapClient([
    'flags' => [
        'service' => ImapConnect::SERVICE_IMAP,
        'encrypt' => ImapConnect::ENCRYPT_SSL,
        'validateCertificates' => ImapConnect::VALIDATE_CERT,
        // Turns debug on or off
        'debug' => ImapConnect::DEBUG,
    ],
    'mailbox' => [
        'remote_system_name' => 'imap.server.ru',
        'port' => 123,
    ],
    'connect' => [
        'username' => 'user',
        'password' => 'pass'
    ]
]);

/* Example 3
 * You can also set the config then connects
 */
ImapClient::setConnectAdvanced();
ImapClient::setConnectConfig([
    'flags' => [
        'service' => ImapConnect::SERVICE_POP3,
        'validateCertificates' => ImapConnect::VALIDATE_CERT,
        'debug' => ImapConnect::DEBUG,
    ],
]);
$imap = new ImapClient();

/* Example 5
 * Here you can see all the options
 */
$imap = new ImapClient([
    'flags' => [
        'service' => ImapConnect::SERVICE_IMAP, # ImapConnect::SERVICE_IMAP ,ImapConnect::SERVICE_POP3, ImapConnect::SERVICE_NNTP
        'encrypt' => ImapConnect::ENCRYPT_SSL, # ImapConnect::ENCRYPT_SSL, ImapConnect::ENCRYPT_TLS, ImapConnect::ENCRYPT_NOTLS
        'validateCertificates' => ImapConnect::NOVALIDATE_CERT, # ImapConnect::VALIDATE_CERT, ImapConnect::NOVALIDATE_CERT
        'secure' => ImapConnect::SECURE, # or null
        'norsh' => ImapConnect::NORSH, # or null
        'readonly' => ImapConnect::READONLY, # or null
        'anonymous' => ImapConnect::ANONYMOUS, # or null
        'debug' => ImapConnect::DEBUG # or null
    ],
    'mailbox' => [
        'remote_system_name' => 'imap.server.ru',
        'port' => null,
        'flags' => null,
        'mailbox_name' => null,
    ],
    'connect' => [
        'mailbox' => null,
        'username' => 'user',
        'password' => 'pass',
        'options' => 0,
        'n_retries' => 0,
        'params' => [],
    ]
]);



namespace program;

mapConnect.php";
n;
use SSilence\ImapClient\ImapConnect;
use SSilence\ImapClient\ImapClient as Imap;

$mailbox = 'my.imapserver.com';
$username = 'username';
$password = 'secret';
$encryption = Imap::ENCRYPT_TLS;

// Open connection
try{
    $imap = new Imap($mailbox, $username, $password, $encryption);
    // You can also check out example-connect.php for more connection options.
}catch (ImapClientException $error){
    echo $error->getMessage().PHP_EOL;
    die();
}

// Get all of the folders as an array of strings
$folders = $imap->getFolders();
foreach($folders as $folder) {
    echo $folder;
}

// Select the folder named INBOX
$imap->selectFolder('INBOX');

// Count the messages in the current folder
$overallMessages = $imap->countMessages();
$unreadMessages = $imap->countUnreadMessages();

// Fetch all of the emails in the current folder
$emails = $imap->getMessages();
var_dump($emails);

// Create a new folder named "Archive"
$imap->addFolder('archive');

// Move the first email from INBOX to our new folder
$imap->moveMessage($emails[0]['uid'], 'archive');

// Delete the second message in INBOX
$imap->deleteMessage($emails[1]['uid']);

# id
    $imap->incomingMessage->header->msgno;
# uid
    $imap->incomingMessage->header->uid;

$imap->incomingMessage->header->details

$imap->incomingMessage->header->details->cc
# or
$imap->incomingMessage->header->details->bcc
# cc and bcc is an array of objects with properties [personal, adl, mailbox, host]

$imap->incomingMessage->message->html
# or
$imap->incomingMessage->message->plain
# or synonym plain
$imap->incomingMessage->message->text

$imap->incomingMessage->message->html->charset

# array
$imap->incomingMessage->message->types

$imap->incomingMessage->attachments[0]->name;
$imap->incomingMessage->attachments[0]->body;
$imap->incomingMessage->attachments[0]->info;

foreach($attachments as $attachment){
    echo $attachment->name;
}

["info"]=>
    object(stdClass)#18 (2) {
      ["structure"]=>
      object(stdClass)#19 (13) {
        ["type"]=>
        int(5)
        ["encoding"]=>
        int(3)
        ["ifsubtype"]=>
        int(1)
        ["subtype"]=>
        string(4) "JPEG"
        ["ifdescription"]=>
        int(0)
        ["ifid"]=>
        int(0)
        ["bytes"]=>
        int(237916)
        ["ifdisposition"]=>
        int(1)
        ["disposition"]=>
        string(10) "attachment"
        ["ifdparameters"]=>
        int(1)
        ["dparameters"]=>
        array(1) {
          [0]=>
          object(stdClass)#25 (2) {
            ["attribute"]=>
            string(8) "filename"
            ["value"]=>
            string(12) "Location.jpg"
          }
        }
        ["ifparameters"]=>
        int(1)
        ["parameters"]=>
        array(1) {
          [0]=>
          object(stdClass)#24 (2) {
            ["attribute"]=>
            string(4) "name"
            ["value"]=>
            string(12) "Location.jpg"
          }
        }
      }
      ["body"]=>string(173862) ""

$imap->incomingMessage->attachment[0]->info->structure
$imap->incomingMessage->attachment[0]->info->body

composer 

# Be sure to add a namespace
use \PHPMailer;

class AdapterForOutgoingMessage
{
# ... code ...

    public function send()
    {
        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->Host = 'smtp1.example.com;smtp2.example.com';
        $mail->SMTPAuth = true;
        $mail->Username = $this->config['connect']['username'];
        $mail->Password = $this->config['connect']['password'];
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        $mail->setFrom(self::$options['fromEmail'], self::$options['fromEmailName']);
        $mail->addAddress(self::$options['toEmail'], self::$options['toEmailName']);
        $mail->addAttachment(self::$options['fileName']);
        $mail->isHTML(true);
        $mail->Subject = self::$options['subject'];
        $mail->Body    = self::$options['messageHtml'];
        $mail->AltBody = self::$options['messagePlain'];
        if(!$mail->send()) {
            throw new ImapClientException('Message could not be sent'.PHP_EOL.$mail->ErrorInfo);
        } else {
            # echo 'Message has been sent';
            return true;
        };
        return false;
    }

# ... code ...
}


use SSilence\ImapClient\AdapterForOutgoingMessage;

try{

$imap = new ImapClient([
    'flags' => [ ... ],
    'mailbox' => [ ... ],
    'connect' => [
        'username' => '[email protected]',
        'password' => 'password',
    ]
]);

# ... code ...

AdapterForOutgoingMessage::setOptions([
    'fromEmail' => '[email protected]',
    'fromEmailName' => 'fromUser',
    'toEmail' => '[email protected]',
    'toEmailName' => 'toUser',
    'fileName' => 'file',
    'subject' => 'subject',
    'messageHtml' => 'message html',
    'messagePlain' => 'message'
]);
$imap->sendMail();

# ... code ...

}catch (ImapClientException $error){
    echo $error->getInfo();
};