搜索
首页后端开发php教程详解使用php-imap查询操作邮件收件箱

本篇文章带大家介绍使用php-imap查询操作邮件收件箱。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

最近在业务场景里有接收解析用户主动发送的邮件,使用php-imap实现了这一需求,记录一下。

确定实现方式

读取邮件的协议有POP3IMAP两种,区别:POP3协议允许电子邮件客户端下载服务器上的邮件,但是在客户端的操作,不会反馈到服务器上。IMAP提供webmail与电子邮件客户端之间的双向通信,客户端的操作都会反馈到服务器上,对邮件进行的操作,服务器上的邮件也会做相应的动作。

需求要求处理完用户的邮件以后,将邮件标记为已处理,因此选用IMAP协议。

安装依赖

本地、服务器php均需要安装imap扩展。在项目的composer.json中添加php-imap(https://github.com/barbushin/php-imap)扩展如下:

"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
        );
    }

获取所有未读邮件列表

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];
}

将某些邮件标记为已读

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

搜索指定主题的邮件并标记为已读

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

推荐学习:《PHP视频教程

以上是详解使用php-imap查询操作邮件收件箱的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:segmentfault。如有侵权,请联系admin@php.cn删除
PHP电子邮件:分步发送指南PHP电子邮件:分步发送指南May 09, 2025 am 12:14 AM

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自动化notifications andMarketingCampaigns.1)设置设置yourphpenvironcormentswironmentswithaweberswithawebserverserverserverandphp,确保themailfunctionisenabled.2)useabasicscruct

如何通过PHP发送电子邮件:示例和代码如何通过PHP发送电子邮件:示例和代码May 09, 2025 am 12:13 AM

发送电子邮件的最佳方法是使用PHPMailer库。1)使用mail()函数简单但不可靠,可能导致邮件进入垃圾邮件或无法送达。2)PHPMailer提供更好的控制和可靠性,支持HTML邮件、附件和SMTP认证。3)确保正确配置SMTP设置并使用加密(如STARTTLS或SSL/TLS)以增强安全性。4)对于大量邮件,考虑使用邮件队列系统来优化性能。

高级PHP电子邮件:自定义标题和功能高级PHP电子邮件:自定义标题和功能May 09, 2025 am 12:13 AM

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP发送电子邮件的指南使用PHP和SMTP发送电子邮件的指南May 09, 2025 am 12:06 AM

使用PHP和SMTP发送邮件可以通过PHPMailer库实现。1)安装并配置PHPMailer,2)设置SMTP服务器细节,3)定义邮件内容,4)发送邮件并处理错误。使用此方法可以确保邮件的可靠性和安全性。

使用PHP发送电子邮件的最佳方法是什么?使用PHP发送电子邮件的最佳方法是什么?May 08, 2025 am 12:21 AM

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

PHP中依赖注入的最佳实践PHP中依赖注入的最佳实践May 08, 2025 am 12:21 AM

使用依赖注入(DI)的原因是它促进了代码的松耦合、可测试性和可维护性。1)使用构造函数注入依赖,2)避免使用服务定位器,3)利用依赖注入容器管理依赖,4)通过注入依赖提高测试性,5)避免过度注入依赖,6)考虑DI对性能的影响。

PHP性能调整技巧和技巧PHP性能调整技巧和技巧May 08, 2025 am 12:20 AM

phperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovesponsemetimes.2)优化

PHP电子邮件安全性:发送电子邮件的最佳实践PHP电子邮件安全性:发送电子邮件的最佳实践May 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中