要使用 PHP SMTP 實現群發郵件,你可以使用 PHPMailer 這樣的庫。以下是使用 PHPMailer 進行群發的步驟:
你可以從 GitHub 上下載 PHPMailer:https://github.com/PHPMailer/PHPMailer
或者通過 Composer 安裝:
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 {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'your_email@example.com'; // SMTP username
$mail->Password = 'your_email_password'; // 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`
//Recipients
$mail->setFrom('your_email@example.com', 'Mailer');
$mail->addAddress('recipient1@example.com', 'Joe User'); // Add a recipient
$mail->addAddress('recipient2@example.com', 'Jane User'); // Add another recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$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}";
}
?>
<?php
$recipients = [
'recipient1@example.com',
'recipient2@example.com',
// Add more recipients here
];
foreach ($recipients as $recipient) {
$mail->clearAddresses();
$mail->addAddress($recipient);
$mail->Subject = 'Here is the subject';
$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';
try {
$mail->send();
echo "Email sent to {$recipient}\n";
} catch (Exception $e) {
echo "Failed to send email to {$recipient}: {$mail->ErrorInfo}\n";
}
}
?>
現在,你可以運行 send_email.php
文件來向所有收件人發送郵件。請注意,為了使這個示例正常工作,你需要將 SMTP 服務器信息、發件人電子郵件地址、密碼和收件人電子郵件地址替換為你自己的。