Home >Backend Development >PHP Tutorial >Detailed explanation of using php-imap to query and operate email inbox

Detailed explanation of using php-imap to query and operate email inbox

藏色散人
藏色散人forward
2021-06-18 16:32:054988browse

This article introduces how to use php-imap to query and operate email inboxes. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Recently, in business scenarios, I have received and parsed emails actively sent by users, and used php-imap to achieve this Requirements, record them.

Determine the implementation method

There are two protocols for reading emails: POP3 and IMAP, the difference is: The POP3 protocol allows email clients to download emails on the server, but operations on the client will not be fed back to the server. IMAP Provides two-way communication between webmail and email clients. Operations on the client will be fed back to the server. For operations on emails, the emails on the server will also take corresponding actions.

The requirement requires that after processing the user's email, the email should be marked as processed, so the IMAP protocol is selected.

Installation dependencies

Both local and server php need to install the imap extension. Add the php-imap (https://github.com/barbushin/php-imap) extension to the project's composer.json as follows:

"require": {
  "php-imap/php-imap": "^3.1",
},

Configure related services

namespace app\library\service\mail;

use PhpImap\Exceptions\ConnectionException;
use PhpImap\Mailbox;

/**
 * 收邮件服务邮件API接口
 * Class PlayService
 * @package app\library\service
 */
class ImapService
{
    public $path = '{imap.263.net:993/imap/ssl}INBOX';   // IMAP server and mailbox folder
    public $login = 'user@263.cn';         // Username for the before configured mailbox
    public $password = 'pwd';                   // Password for the before configured username
    public $dir = null;        // Directory, where attachments will be saved (optional)
    public $encoding = 'UTF-8';   // Server encoding (optional)

    public $mailbox;

    public function __construct()
    {
        $this->mailbox = new Mailbox(
            $this->path,
            $this->login,
            $this->password,
            $this->dir,
            $this->encoding
        );
    }

Get a list of all unread messages

public function unSeenList()
{
    try {
        $mail_ids = $this->mailbox->searchMailbox('UNSEEN');
    } catch (ConnectionException $ex) {
        die('IMAP connection failed: ' . $ex->getMessage());
    } catch (\Exception $ex) {
        die('An error occured: ' . $ex->getMessage());
    }

    // If $mailsIds is empty, no emails could be found
    if (!$mail_ids) {
        die('Mailbox is empty');
    }

    try {
        $info = $this->mailbox->getMailsInfo($mail_ids);
    } catch (ConnectionException $ex) {
        echo "IMAP connection failed: " . $ex;
        die();
    }
    return ['ids' => $mail_ids, 'list' => $info];
}

Mark certain messages as read

/**
 * @param array $mail_ids
 * @return mixed
 */
public function markRead($mail_ids)
{
    return $this->mailbox->markMailsAsRead($mail_ids);
}

Search for messages with specified topics and mark them as read

$imap = new ImapService();
$condition = 'UNSEEN  SUBJECT "' . $title . '" SINCE "' . date('Y-m-d', strtotime('-1 days')) . '" FROM ' . $mail;
$data['mail'] = $imap->mailbox->searchMailbox($condition);
if (!empty($data['mail'])) {
    $data['info'] = $imap->mailbox->getMailsInfo($data['mail']);
    if ($params['mark'] == 1) {
        $data['mark'] = $imap->markRead(array_column($data['info'], 'uid'));
    }
}

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Detailed explanation of using php-imap to query and operate email inbox. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete