要使用PHP發(fā)送帶附件的電子郵件,您可以使用PHPMailer庫(kù)。以下是使用PHPMailer發(fā)送帶附件的電子郵件的步驟:
composer require phpmailer/phpmailer
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// 郵件服務(wù)器設(shè)置
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // 開啟詳細(xì)調(diào)試輸出
$mail->isSMTP(); // 設(shè)置郵件發(fā)送使用SMTP協(xié)議
$mail->Host = 'smtp.example.com'; // 設(shè)置郵件發(fā)送服務(wù)器的地址
$mail->SMTPAuth = true; // 開啟使用SMTP認(rèn)證功能
$mail->Username = 'your_email@example.com'; // 設(shè)置發(fā)送郵件的用戶名
$mail->Password = 'your_email_password'; // 設(shè)置發(fā)送郵件的密碼
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // 設(shè)置加密類型
$mail->Port = 465; // 設(shè)置郵件發(fā)送端口
// 發(fā)件人和收件人
$mail->setFrom('your_email@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
// 附件
$mail->addAttachment('/path/to/your/attachment.ext', 'Attachment Name');
// 郵件內(nèi)容
$mail->isHTML(true); // 設(shè)置郵件正文格式為HTML
$mail->Subject = 'Email with Attachment'; // 設(shè)置郵件主題
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
smtp.example.com
:將其替換為您的郵件服務(wù)器地址。your_email@example.com
:將其替換為您的發(fā)件人電子郵件地址。your_email_password
:將其替換為您的發(fā)件人電子郵件密碼。/path/to/your/attachment.ext
:將其替換為您要附加的文件路徑和擴(kuò)展名。recipient@example.com
:將其替換為收件人的電子郵件地址。Recipient Name
:將其替換為收件人的名稱。Attachment Name
:將其替換為您要附加的文件名稱。php send_email_with_attachment.php
現(xiàn)在,您應(yīng)該能夠成功發(fā)送帶有附件的電子郵件。如果您遇到任何問(wèn)題,請(qǐng)檢查您的郵件服務(wù)器設(shè)置和電子郵件憑據(jù)是否正確。