Php mail multiple recipients

In PHP, you can send an email to multiple recipients using the mail() function or a PHP mail library like PHPMailer. Here are some examples:

Using the mail() function:

$to = array('[email protected]', '[email protected]', '[email protected]');
$subject = 'Test email to multiple recipients';
$message = 'This is a test email sent to multiple recipients';

$headers = 'From: [email protected]'. "\r\n".
           'Reply-To: [email protected]'. "\r\n".
           'MIME-Version: 1.0'. "\r\n".
           'Content-Type: text/plain; charset=UTF-8';

mail($to, $subject, $message, $headers);

In this example, the mail() function is called with an array of recipient email addresses, the subject, message, and headers.

Using PHPMailer:

require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();

$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$to = array('[email protected]', '[email protected]', '[email protected]');
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress($to);

$mail->Subject = 'Test email to multiple recipients';
$mail->Body = 'This is a test email sent to multiple recipients';

if (!$mail->send()) {
    echo 'Error sending email: '. $mail->ErrorInfo;
} else {
    echo 'Email sent successfully!';
}

In this example, we create a new instance of the PHPMailer class and set up the SMTP settings. We then add the recipient email addresses using the addAddress() method and set the subject and body of the email. Finally, we call the send() method to send the email.

Using a loop:

$to = array('[email protected]', '[email protected]', '[email protected]');
$subject = 'Test email to multiple recipients';
$message = 'This is a test email sent to multiple recipients';

foreach ($to as $recipient) {
    $headers = 'From: [email protected]'. "\r\n".
               'Reply-To: [email protected]'. "\r\n".
               'MIME-Version: 1.0'. "\r\n".
               'Content-Type: text/plain; charset=UTF-8';
    mail($recipient, $subject, $message, $headers);
}

In this example, we use a loop to iterate over the array of recipient email addresses and send an email to each one using the mail() function.

Note that when sending emails to multiple recipients, it's a good idea to use a loop or a library like PHPMailer to avoid having to repeat the same code for each recipient. Additionally, be sure to check the email addresses for validity and handle any errors that may occur during the sending process.