溫馨提示×

php stmp 如何實現(xiàn)群發(fā)郵件

PHP
小樊
81
2024-09-24 12:15:08
欄目: 編程語言

要使用 PHP SMTP 實現(xiàn)群發(fā)郵件,你可以使用 PHPMailer 這樣的庫。以下是使用 PHPMailer 進行群發(fā)的步驟:

  1. 下載并安裝 PHPMailer

你可以從 GitHub 上下載 PHPMailer:https://github.com/PHPMailer/PHPMailer

或者通過 Composer 安裝:

composer require phpmailer/phpmailer
  1. 創(chuàng)建一個 PHP 文件(例如:send_email.php)并引入 PHPMailer 類
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);
  1. 配置 SMTP 服務(wù)器信息
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`
  1. 設(shè)置發(fā)件人、收件人和郵件內(nèi)容
    //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';
  1. 發(fā)送郵件并檢查結(jié)果
    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
  1. 遍歷收件人列表并群發(fā)郵件
<?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";
    }
}
?>

現(xiàn)在,你可以運行 send_email.php 文件來向所有收件人發(fā)送郵件。請注意,為了使這個示例正常工作,你需要將 SMTP 服務(wù)器信息、發(fā)件人電子郵件地址、密碼和收件人電子郵件地址替換為你自己的。

0