PHP

php stmp 如何实现群发邮件

小樊
82
2024-09-24 12:15:08
栏目: 编程语言

要使用 PHP SMTP 实现群发邮件,你可以使用 PHPMailer 这样的库。以下是使用 PHPMailer 进行群发的步骤:

  1. 下载并安装 PHPMailer

你可以从 GitHub 上下载 PHPMailer:https://github.com/PHPMailer/PHPMailer

或者通过 Composer 安装:

composer require phpmailer/phpmailer
  1. 创建一个 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 服务器信息
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. 设置发件人、收件人和邮件内容
    //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. 发送邮件并检查结果
    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
  1. 遍历收件人列表并群发邮件
<?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 服务器信息、发件人电子邮件地址、密码和收件人电子邮件地址替换为你自己的。

0
看了该问题的人还看了