At a time multiple send mails in php
A common question!
In PHP, you can send multiple emails at once using a loop or an array of email addresses. Here are a few ways to do it:
Method 1: Using a loop
$mails = array(
'[email protected]' => 'Subject 1',
'[email protected]' => 'Subject 2',
'[email protected]' => 'Subject 3'
);
foreach ($mails as $to => $subject) {
$headers = 'From: Your Name <[email protected]>'. "\r\n";
$headers.= 'Reply-To: '. $to. "\r\n";
$headers.= 'MIME-Version: 1.0'. "\r\n";
$headers.= 'Content-Type: text/plain; charset=UTF-8'. "\r\n";
$message = 'Hello, this is a test email';
mail($to, $subject, $message, $headers);
}
In this example, we define an array of email addresses and subjects. We then loop through the array using a foreach
loop, and for each iteration, we send an email using the mail()
function.
Method 2: Using an array of email addresses
$to = array('[email protected]', '[email protected]', '[email protected]');
$subject = 'Test Email';
$message = 'Hello, this is a test email';
$headers = 'From: Your Name <[email protected]>'. "\r\n";
$headers.= 'Reply-To: '. implode(', ', $to). "\r\n";
$headers.= 'MIME-Version: 1.0'. "\r\n";
$headers.= 'Content-Type: text/plain; charset=UTF-8'. "\r\n";
mail($to, $subject, $message, $headers);
In this example, we define an array of email addresses and send a single email to all of them using the mail()
function. We use the implode()
function to concatenate the email addresses into a single string.
Method 3: Using a library like SwiftMailer
require_once 'SwiftMailer.php';
$mailer = new Swift_Mailer(new Swift_SendmailTransport());
$to = array('[email protected]', '[email protected]', '[email protected]');
$subject = 'Test Email';
$message = 'Hello, this is a test email';
$message = Swift_Message::newInstance()
->setSubject($subject)
->setFrom(array('[email protected]' => 'Your Name'))
->setTo($to)
->setBody($message, 'text/plain');
$mailer->send($message);
In this example, we use the SwiftMailer library to send multiple emails at once. We define an array of email addresses and create a new Swift_Message
object. We then set the subject, from address, and to addresses, and finally send the email using the send()
method.
Remember to replace the placeholders ([email protected]
, [email protected]
, etc.) with your actual email addresses and settings.