PHP code example of unyii2 / yii2-imap

1. Go to this page and download the library: Download unyii2/yii2-imap 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/ */

    

unyii2 / yii2-imap example snippets


'components' => [
      ...
      'imap' => [
         'class' => 'unyii2\imap\Imap',
         'connection' => [
              'imapPath' => '{imap.gmail.com:993/imap/ssl}INBOX',
              'imapLogin' => 'username',
              'imapPassword' => 'password',
              'serverEncoding'=>'encoding', // utf-8 default.
              'attachmentsDir'=>'/'
        ],
    ],
    ...
 ],


//4th Param _DIR_ is the location to save attached files 
//Eg: /path/to/application/mail/uploads.
$mailbox = new unyii2\Mailbox(yii::$app->imap->connection);


$imapConnection = new unyii2\imap\ImapConnection

$imapConnection->imapPath = '{imap.gmail.com:993/imap/ssl}INBOX';
$imapConnection->imapLogin = 'username';
$imapConnection->imapPassword = 'password';
$imapConnection->serverEncoding = 'encoding'; // utf-8 default.
$imapConnection->attachmentsDir = '/';


//4th Param _DIR_ is the location to save attached files 
//Eg: /path/to/application/mail/uploads.
$mailbox = new unyii2\Mailbox($imapConnection);

$mailbox->searchMailBox(ALL)// Prints all Mail ids.
print_r($mailIds);

foreach($mailIds as $mailId)
{
    // Returns Mail contents
    $mail = $mailbox->getMail($mailId); 

    if(alreadyProcesedMessage($mail->messageId)){
        continue;
    }

    // Use, if $mailbox->readMailParts = false; 
    // Read mail parts (plain body, html body and attachments
    $mail = $mailbox->getMailParts($mail);

    // Returns mail attachements if any or else empty array
    $attachments = $mail->getAttachments(); 
    foreach($attachments as $attachment){
        echo ' Attachment:' . $attachment->name . PHP_EOL;
        
        // Delete attachment file
        unlink($attachment->filePath);

    }
}

//Mark a mail to delete</span></span> 
$mailbox->deleteMail($mailId); // Deletes all marked mails
$mailbox->expungeDeletedMails();