search
HomeBackend DevelopmentPHP TutorialDetailed explanation of using php-imap to query and operate email inbox

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",
},
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. If there is any infringement, please contact admin@php.cn delete
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft