php實現(xiàn)收發(fā)郵件的方法詳解
更新時間:2023年11月01日 16:43:25 作者:AreoWarm
這篇文章主要為大家詳細介紹了php實現(xiàn)收發(fā)郵件的多種方法總結,文中的示例代碼講解詳細,具有一定的學習價值,感興趣的小伙伴可以跟隨小編一起了解下
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: 方法一 郵件發(fā)送與接收 -- 如果亂碼需要配置 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`
//測發(fā)送 -- 成功
$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);
// 獲取郵件主題、發(fā)件人、正文等信息
$subject = $email->subject;//正文text內容
$from = $email->fromName;//發(fā)送者 **@qq.com
$textHtml = $email->textHtml;//正文html內容
$date = $email->date;//收件時間
$getAttachments = $email->getAttachments();//附件數(shù)組
$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);
// }
// 在這里可以執(zhí)行你的邏輯,例如將郵件信息寫入數(shù)據庫或者進行其他處理
}
}
}
方法二結果如圖所示:

以上就是php實現(xiàn)收發(fā)郵件的方法詳解的詳細內容,更多關于php收發(fā)郵件的資料請關注腳本之家其它相關文章!
相關文章
讓PHP以ROOT權限執(zhí)行系統(tǒng)命令的方法
這種問題我想大家可能都遇到過,網友提供的解決方法也很多。我也只是結合自己系統(tǒng)的需求并結合網友的解決方案來總結的一種方法2011-02-02

