PHPackages                             ssilence/php-imap-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Mail &amp; Notifications](/categories/mail)
4. /
5. ssilence/php-imap-client

ActiveLibrary[Mail &amp; Notifications](/categories/mail)

ssilence/php-imap-client
========================

Php imap client

3.0(7mo ago)271191.7k↓25.5%131[43 issues](https://github.com/SSilence/php-imap-client/issues)[1 PRs](https://github.com/SSilence/php-imap-client/pulls)4MITPHPPHP &gt;=8.1

Since Sep 21Pushed 5mo ago34 watchersCompare

[ Source](https://github.com/SSilence/php-imap-client)[ Packagist](https://packagist.org/packages/ssilence/php-imap-client)[ Docs](https://github.com/SSilence/php-imap-client)[ RSS](/packages/ssilence-php-imap-client/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (2)Used By (4)

Welcome to php-imap-client
==========================

[](#welcome-to-php-imap-client)

Hello! This is php-imap-client. This is a simple and easy to use library for connecting to imap servers and working with the emails inside. Our well-known features are:

- simple interface
- Get emails and folders
- Move, delete, count emails
- Rename, delete and
- Get attachments
- Many more

Click to open [documentation](https://ssilence.github.io/php-imap-client/)

Caution

php-imap-client base on the IMAP extensions. From PHP 8.4 it will [move from PHP core to PECL](https://php.watch/versions/8.4/imap-unbundled). The IMAP extension can still be installed from PECL but the [Webklex/php-imap library](https://github.com/Webklex/php-imap) doesn't need any extension.

Documentation
=============

[](#documentation)

1. [Getting started](#getting-started)
2. [Connecting](#connecting)
3. [Errors](#errors)
4. [Installing](#installing)
5. [Methods](#methods)
6. [Usage](#usage)
7. [Examples](#examples)
8. [Incoming Message](#incoming-message)
9. [Sending Emails](#sending-emails)
10. [License](#license)

Getting started
---------------

[](#getting-started)

In order to get started, we first need to get php-imap-client to your code base.
There are currently two ways of doing this.

### 1) Composer

[](#1-composer)

`composer require ssilence/php-imap-client:^3.0`

```
require_once "vendor/autoload.php";
```

### 2) Manually

[](#2-manually)

1. Download the files from github or the releases page
2. Extract the files into the folder you wish
3. In the file that will call methods add

```
require_once "path/to/ImapClientException.php";
require_once "path/to/ImapConnect.php";
require_once "path/to/ImapClient.php";
require_once "path/to/IncomingMessage.php";
require_once "path/to/TypeAttachments.php";
require_once "path/to/TypeBody.php";
```

After this, we need to let php we need these classes:

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

Next, we need to declare out variables:

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

Next, we need to open the connection:

```
// 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
}
```

After that we can do all this fun stuff :)

```
// 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']);
```

Connecting
----------

[](#connecting)

### Default connnection

[](#default-connnection)

A default connection is the easy and most uncommon way to connect to an imap sever. Use the code below to use our default connection method.

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

This code does not check for errors and assumeing everything is right. If you are using this in production be sure to check for errors

### Advanced Connecting

[](#advanced-connecting)

We also have ways to change how your connection works. Read the code and examples below to learn some ways to modifiy your connection,

```
/* 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' => [],
    ]
]);
```

Errors
------

[](#errors)

Many errors may be thrown while using the library, if you cant seem to find what an error means or what you are doing wrong, take a look here. Everything is structured like this:

ErrorDescriptionSolution/Note**Imap function not available**PHP does not support connections to web servers via imapTo fix this download the php\_imap.dll and enable it by putting the following text in php.ini `extension=php_gettext.dll`**Mailbox is not installed**No mail box was providedConfirm that the $mailbox variable is filled when connecting**Mailbox must be a string**The mailbox provided to connect to the web server is not a stringWe cannot connect to mail boxes that have a integer in them. Make sure the $mailbox variable provied is a string**Username must be a string**The username provided to connect to the web server is not a stringWeb servers dont use arrays as usernames!!! Make sure the $username variable is a string**Password must be a string**The password provided to connect to the web server is not a stringConfirm that the $password variable is a string**Options must be an integer**The options variable provided when connecting is not an integer// Dont know. Someone checking pr tell me and ill fix**N\_ must be an integer**The number of retries provided is not an integerMake sure that the $N\_retries variable is an integer**Params must be an array**The parameters provided to connect to the server are not an array// Dont know. Someone checking pr tell me and ill fix**Error connecting to \[insert your mailbox string here\]**PHP-imap client had trouble connecting to the provided mailbox with the provided detailsThis can mean many things. It can mean your mailbox is invalid or your username and password are not valid. Comfirm your login details and make sure your mail server is online**Option connect must be installed**If you selected the advanced connection and not installed `connect` option like```
$imap = new ImapClient([    'connect' => [        'username' => 'user',        'password' => 'pass',    ]]);
```

**File must be specified for saveEmail()**You did not specify a file pathInsure your code looks like this:
```
$imap->saveEmail($your_file_path_var, $your_email_id_var, $your_part_var)
```

**Email id must be specified for saveEmail()**You did not specify an email idInsure your code looks like this:
```
$imap->saveEmail($your_file_path_var, $your_email_id_var, $your_part_var)
```

**File must be a string for saveEmail()**The provided file path is not a stringMake sure your $file is a string *not* a open file**$id must be a integer for saveEmail()**The provided email id is an integerMake sure your $id is an integer**What to use id or uid?**You did not let us know weather to use id or uuidsInstalling
----------

[](#installing)

PHP-imap-client can be installed 2 ways. The first composer and the second manual

### 1) Composer

[](#1-composer-1)

Use the following command to install php-imap-client library: `composer require ssilence/php-imap-client:^3.0`

### 2) Manual

[](#2-manual)

1. Download the files from github or the releases page
2. Extract the files into the folder you wish
3. In the file that will call methods add

```
require_once "path/to/ImapClientException.php";
require_once "path/to/ImapConnect.php";
require_once "path/to/ImapClient.php";
require_once "path/to/IncomingMessage.php";
require_once "path/to/TypeAttachments.php";
require_once "path/to/TypeBody.php";
```

You may then use connect etc

Methods
-------

[](#methods)

The following methods are currently available.

MethodDescription`__construct($mailbox, $username, $password, $encryption)`open new imap connection`isConnected()`check whether the imap connection was opened successfully`getError()`returns the last error message.`getFolders($separator, $type)`@param string $separator. Default is '.' @param int $type. Has three meanings 0,1,2. If 0 returns a nested array, if 1 it returns an array of strings, if 2 returns raw data from imap\_list().`getMessage($id)`get email by given id.`getMessages($number, $start, $order)`get emails in current folder.`getUnreadMessages($read)`get unread messages in current folder and mark them read. Use $read = false marks them unread.`getQuota($user)`Retrieve the quota level settings, and usage statics per mailbox.`getQuotaRoot($user)`Retrieve the quota level settings, and usage statics per mailbox.`getAllEmailAddresses()`returns all email addresses of all emails (for auto suggestion list).`getMailboxStatistics()`returns statistics, see [imap\_mailboxmsginfo](https://php.net/manual/en/function.imap-mailboxmsginfo.php).`getHeaderInfo($msgNumber)`Get the header info via the message number. `getMessagesByCriteria($criteria, $number, $start, $order)`Get messages by criteria like 'FROM uncle'.`getBriefInfoMessages()`Get a short information about the messages in the current folder.`getSection($id, $section)`Get the section of the specified message.`getUid($id)`Get uid through id.`getId($uid)`Get id through uid.`setUnseenMessage($id, $seen = true)`set unseen state of the message with given id.`setEmbed($val)`If true, embed all 'inline' images into body HTML, accesible in 'body\_embed'.`setEncoding()`Identify encoding by charset attribute in header.`selectFolder($folder)`select the provided folder.`countMessages()`count the messages in current folder.`countUnreadMessages()`count the unread messages in current folder.`deleteMessage($id)`delete message with given id.`deleteMessages($ids)`delete messages with given ids (as array).`moveMessage($id, $target)`move message with given id in new folder`moveMessages($ids, $target)`move messages with given ids (as array) in new folder`addFolder($name)`add new folder with given name`removeFolder($name)`delete folder with given name`renameFolder($name, $newname)`rename folder with given name`purge()`move all emails in the current folder into trash. emails in trash and spam will be deleted.`convertToUtf8()`Apply encoding defined in header`saveMessageInSent($header, $body)`save a sent message in sent folder`saveEmail($file , $id, $part)`saves an email to the $file file`saveEmailSafe($file , $id, $part, $streamFilter)`saves an email to the $file file. This is recommended for servers with low amounts of RAM. Stream filter is set to convert.base64-decode by default.`saveAttachments($options)`Save attachments one incoming message. You can set any of the options: `$options['dir'=>null, 'incomingMessage'=>null]`.`saveAttachmentsMessagesBySubject($subject, $dir = null, $charset = null)`Save Attachmets Messages By Subject`sendMail()`Send a message using the adapter.Usage
-----

[](#usage)

### After install prep

[](#after-install-prep)

After you install this library ensure you have added the required classes. A basic connection may look like this:

```
$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();
};
```

The above code connects you to a mail server and makes sure it connected. Change the variables to your information

### After connection

[](#after-connection)

There are many things you can do after the code above. For example you can get and echo all folders

```
$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;
}
```

See [getFolders()](Methods.md) method settings. You can also select folders

```
$imap->selectFolder("Inbox");
```

Once you selected a folder you can count the number of messages in the folder:

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

To get a brief summary of all messages in the current folder, including the message ID you can use this

```
$imap->getBriefInfoMessages()
```

Get the message with ID 82

```
$imap->getMessage(82)
```

Save all of the attachmets in this email.

```
$imap->saveAttachments();
```

or

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

or save the attachment(s) like this

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

It is also possible to save all attachments for messages with a special word in the message subject.

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

Get the header info like cc and bcc

```
var_dump(getHeaderInfo(1));
```

Get all unread messages.

```
$imap->getUnreadMessages()
```

Okay, now lets fetch all emails in the currently selected folder (in our example the "Inbox"):

```
$emails = $imap->getMessages();
```

Now $emails it is array object.

The structure of a single message when it is received by the method getMessage() or getMessages() it by the look here [Incoming Message](IncomingMessage.md)

For example get subject and simple text messages

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

You can also add/rename/delete folders. Lets add a new folder:

```
$imap->addFolder('archive');
```

Now we move the first email into this folder

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

And we delete the second email from inbox

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

We also can save emails

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

You can use the method of sending messages.

```
$imap->sendMail();
```

But for this you need to take several steps. [Adapter for outgoing message. Use in 3 steps.](AdapterForOutgoingMessage.md)

For a full list of methods you can do check [current list of methods](Methods.md).

### Advanced connecting

[](#advanced-connecting-1)

You can also use the below code to add some more options while connecting

```
$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
    ]
]);
```

All connecting options you can see in example-connect.php file or go [Advanced connecting](AdvancedConnecting.md)or you can see code ImapConnect class.

Examples
--------

[](#examples)

### Composer

[](#composer)

```
