php收发邮件的多种方法?

1、添加扩展:

# 第一种:
composer require php-imap/php-imap
# 第二种:
composer require phpmailer/phpmailer

2、这里采用第二种方式:

<?php
declare(strict_types=1);

namespace App\Controller\v1\email;


use App\Controller\AbstractController;
use PhpImap\Exception;
use PhpImap\Mailbox;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

/**
 * Desc: 电子邮件相关 
 */
class EmailController extends AbstractController
{

    public const imapServer = '{imap.qq.com:993/imap/ssl}'; // QQ 邮箱的 IMAP 服务器地址
    public const imapUsername = '11***039@qq.com'; // 您的 QQ 邮箱地址
    public const imapPassword = '***';  // 您的 QQ 邮箱密码
    public const attachmentPath = BASE_PATH . '/storage/email/'; // 您的 附件 保存目录


    /**
     * Desc: 方法一 邮件发送与接收 -- 如果乱码需要配置 GB2312  UTF-8 
     * Date: 2023-10-31 18:38
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function receiveMailWithAttachments()
    {
        $params = $this->request->post();
        $imapServer = $params['imapServer'] ?? self::imapServer; // QQ 邮箱的 IMAP 服务器地址
        $smtpServer = $params['smtpServer'] ?? self::imapServer; // QQ 邮箱的 smtp 服务器地址
        $imapUsername = $params['imapUsername'] ?? self::imapUsername; // 您的 QQ 邮箱地址
        $imapPassword = $params['imapPassword'] ?? self::imapPassword; // 您的 QQ 邮箱密码
        var_dump($imapServer, $smtpServer, $imapUsername, $imapPassword);
        $mail = new PHPMailer(true);
        try {
            //Server settings
            $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host = $smtpServer;//'smtp.example.com';                     //Set the SMTP server to send through
            $mail->SMTPAuth = true;                                   //Enable SMTP authentication
            $mail->Username = $imapUsername;//'user@example.com';                     //SMTP username
            $mail->Password = $imapPassword;                               //SMTP password
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
            $mail->Port = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

            //测发送 -- 成功
            $mail->setFrom($imapUsername, 'Mailer');
            $mail->addAddress('28***511@qq.com', 'John Doe');
            $mail->Subject = 'PHPMailer SMTP test';
            $mail->Body = 'This is a test email message';
            if (!$mail->send()) {
                echo 'Message could not be sent.' . "\n";
                echo 'Mailer Error: ' . $mail->ErrorInfo . "\n";
            } else {
                echo 'Message has been sent' . "\n";
            }

            $msg_id = $mail->getLastMessageID();
            echo "LastMessageID => " . $msg_id . "\n";

            //测收件
            $inbox = imap_open($imapServer, $imapUsername, $imapPassword);
            $result = imap_search($inbox, 'UNSEEN');

            foreach ($result as $mail_id) {
                $structure = imap_fetchstructure($inbox, $mail_id);
                for ($i = 0; $i < count($structure->parts); $i++) {
                    if ($structure->parts[$i]->ifdparameters) {
                        foreach ($structure->parts[$i]->dparameters as $object) {
                            if (strtolower($object->attribute) == 'filename') {
                                $filename = $object->value;
                                $file_data = imap_fetchbody($inbox, $mail_id, (string)($i + 1));
                                $file_mime = imap_fetchmime($inbox, $mail_id, (string)($i + 1));
                                $file_text = imap_fetchtext($inbox, $mail_id);
                                $file_structure = imap_fetchstructure($inbox, $mail_id);
                                // 处理附件内容...
                                var_dump('读取1 file:[' . $mail_id . ']', $filename, $file_mime, $file_text, $file_structure);

                                // 将附件保存到指定目录
                                file_put_contents(self::attachmentPath . $filename, $file_data);
                            }
                        }
                    }
                }
            }
            imap_close($inbox);
        } catch (\Throwable $e) {
            echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
            var_dump($e->getLine() . ' ' . $e->getMessage());
        }
        return response_api(200, 'success');
    }


    /** 方法二 邮件接收
     * @throws Exception
     */
    public function receiveMailWithAttachmentsImap()
    {
        $params = $this->request->post();
        $imapServer = $params['imapServer'] ?? self::imapServer; // QQ 邮箱的 IMAP 服务器地址
        $smtpServer = $params['smtpServer'] ?? self::imapServer; // QQ 邮箱的 smtp 服务器地址
        $imapUsername = $params['imapUsername'] ?? self::imapUsername; // 您的 QQ 邮箱地址
        $imapPassword = $params['imapPassword'] ?? self::imapPassword; // 您的 QQ 邮箱密码
        $attachmentPath = $params['attachmentPath'] ?? self::attachmentPath; // 您的附件存放地址
        var_dump($imapServer, $smtpServer, $imapUsername, $imapPassword);
        $mailbox = new PHPMailer(true);
        $mailbox->isSMTP();
        $mailbox = new Mailbox($imapServer, $imapUsername, $imapPassword, $attachmentPath);

        $mailIds = $mailbox->searchMailbox('UNSEEN'); // 搜索未读邮件
        var_dump('-------------2--------------', $mailIds);
        foreach ($mailIds as $mailId) {
            $email = $mailbox->getMail($mailId);

            // 获取邮件主题、发件人、正文等信息
            $subject = $email->subject;//正文text内容
            $from = $email->fromName;//发送者 **@qq.com
            $textHtml = $email->textHtml;//正文html内容
            $date = $email->date;//收件时间
            $getAttachments = $email->getAttachments();//附件数组
            $fromAddress = $email->fromAddress;//来件者地址名称 **@qq.com
            $fromName = $email->fromName;//来件者姓名

            var_dump($subject);
            var_dump($from);
            var_dump($textHtml);
            var_dump($date);
            var_dump($getAttachments);
            var_dump($fromAddress);
            var_dump($fromName);
            // 处理附件
//            foreach ($getAttachments as $attachment) {
//                $filename = $attachment->name;
//                $filePath = $attachment->filePath;
//
//                // 将附件保存到指定目录
                file_put_contents($attachmentPath . $filename, $contents);
//            }

            // 在这里可以执行你的逻辑,例如将邮件信息写入数据库或者进行其他处理
        }
    }

}

方法二结果如图所示:

相关推荐
qq_2518364571 小时前
基于PHP技术的在线校园美食攻略程序设计与实现
uni-app·php·美食
Mac@分享吧2 小时前
PhpStorm 2024 for Mac PHP集成开发工具
ide·macos·php·phpstorm·php语言
Unity打怪升级11 小时前
Laravel: 优雅构建PHP应用的现代框架
开发语言·php·laravel
逼子格17 小时前
55、定义浅层神经网络架构和算法(matlab)
开发语言·深度学习·神经网络·php·神经网络架构
kali-Myon18 小时前
ctfshow-web入门-命令执行(web118详解)Linux 内置变量与Bash切片
前端·学习·web安全·php·bash·web
强生1990020519 小时前
PHP 使用RabbitMq推送消息
开发语言·后端·rabbitmq·php
智商不在服务器1 天前
网络防御保护——网络安全概述
网络·web安全·php
Unity打怪升级1 天前
Symfony框架:优雅构建PHP应用的强有力工具
开发语言·php·symfony
Knock man1 天前
VMware虚拟机配置桥接网络
开发语言·网络·php
pk_xz1234561 天前
如何使用thinkPHP3.2.* 版本开发
php