Home  >  Article  >  Backend Development  >  How to send emails in batches in php

How to send emails in batches in php

PHPz
PHPzforward
2024-03-01 19:10:21821browse

php editor Xigua teaches you how to use PHP's mail() function to send emails in batches. By writing a loop, iterate through the mailing list and send the mails one by one. Variables can be used in email content to personalize each email and increase interactivity. Remember to set an appropriate delay to avoid being intercepted by the server. Through simple code implementation, you can easily implement the function of sending emails in batches and improve work efficiency!

The following is a sample code for sending emails in batches using the phpMailer library:

require 'phpmailer/PHPMailerAutoload.php';

// 创建一个新的 PHPMailer 对象
$mail = new PHPMailer();

// 设置邮件服务器的参数
$mail->iSSMTP();
$mail->Host = 'smtp.example.com';// 邮件服务器的主机名
$mail->Port = 587;// 邮件服务器的端口号
$mail->SMTPAuth = true;// 启用 SMTP 认证
$mail->Username = 'your_username';// 邮件服务器的用户名
$mail->PassWord = 'your_password';// 邮件服务器的密码
$mail->SMTPSecure = 'tls';// 使用 TLS 加密连接

// 设置邮件的发送者和接收者
$mail->setFrom('sender@example.com', 'Sender Name');// 发件人邮箱和名称
$mail->addAddress('recipient1@example.com', 'Recipient 1');// 收件人邮箱和名称
$mail->addAddress('recipient2@example.com', 'Recipient 2');// 可以添加多个收件人
$mail->addAddress('recipient3@example.com', 'Recipient 3');

// 设置邮件的主题和内容
$mail->Subject = 'Test Subject';
$mail->Body = 'This is a test email.';

// 发送邮件
if ($mail->send()) {
echo 'Email sent successfully';
} else {
echo 'Error: ' . $mail->ErrorInfo;
}

In the above code, we first introduced the PHPMailer library, and then created a new PHPMailer object. Next, we set the parameters of the mail server, including host name, port number, SMTP authentication, etc. Then, we set up the sender and recipient of the email, and can add multiple recipients. Finally, we set the subject and content of the email and call the $mail->send() method to send the email.

Of course, the above code is just a simple example, and more complex logic may be required in actual applications, such as obtaining the recipient list from the database , formatting the email, adding attachments, etc. You can modify and extend it according to your specific needs.

The above is the detailed content of How to send emails in batches in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete