What are the best practices for setting and clearing recipient addresses when sending multiple emails with PHPmailer?
When sending multiple emails with PHPmailer, it is important to set and clear recipient addresses properly to avoid sending emails to unintended recipients. To achieve this, you should set the recipient address before sending each email and then clear the address after sending the email to ensure it does not carry over to the next email.
// Initialize PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
// Loop through recipient addresses and send emails
$recipients = ['recipient1@example.com', 'recipient2@example.com', 'recipient3@example.com'];
foreach ($recipients as $recipient) {
$mail = new PHPMailer(true);
try {
// Set recipient address
$mail->addAddress($recipient);
// Set other email parameters
$mail->setFrom('your@example.com', 'Your Name');
$mail->Subject = 'Subject';
$mail->Body = 'Email body content';
// Send email
$mail->send();
// Clear recipient address
$mail->clearAddresses();
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}