What is the recommended method for sending emails to multiple users with attachments using PHP?
When sending emails to multiple users with attachments using PHP, it is recommended to use a loop to iterate through the list of recipients and attach the files before sending the email. This ensures that each recipient receives the email with the appropriate attachment.
<?php
// List of recipients
$recipients = array('recipient1@example.com', 'recipient2@example.com');
// Email subject
$subject = 'Email with attachments';
// Email message
$message = 'Please see the attached files.';
// File paths
$attachments = array('file1.pdf', 'file2.jpg');
// Send email to each recipient with attachments
foreach($recipients as $recipient) {
$headers = 'From: sender@example.com' . "\r\n";
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('sender@example.com', 'Sender Name');
$mail->addAddress($recipient);
$mail->Subject = $subject;
$mail->Body = $message;
foreach($attachments as $attachment) {
$mail->addAttachment($attachment);
}
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
}
?>
Keywords
Related Questions
- How can one prevent the error message "Possible file upload attack!" when using the move_uploaded_file function in PHP?
- What methods can be used to filter events from multiple calendars when using the Google Calendar API in PHP?
- What is the purpose of the if-else statement in the PHP script provided in the forum thread?