Using the batchSend() Method
The batchSend() method of the Swift_Mailer class sends a separate message to each recipient in the To: field. Each recipient receives a message containing only their own address in the To: field.
To send a Message with batchSend():
- Create a Transport from one of the provided Transports – Swift_SmtpTransport, Swift_SendmailTransport, Swift_MailTransport or one of the aggregate Transports.
- Create an instance of the Swift_Mailer class, using the Transport as it's constructor parameter.
- Create a Message according to the instructions laid out in Creating Messages
- Send the message via the batchSend() method on the Mailer object.
Each recipient of the messages receives a different copy with only their own email address on the To: field. An integer is returned which includes the number of successful recipients. If none of the recipients could be sent to then zero will be returned, which equates to a boolean false. If you set two To: recipients and three Bcc: recipients in the message and all of the recipients are delivered to successfully then the value 5 will be returned.
<?php
require_once 'lib/swift_required.php';
//Create the Transport
$transport = Swift_SmtpTransport::newInstance('localhost', 25);
//Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
//Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john@doe.com' => 'John Doe'))
->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
->setBody('Here is the message itself')
;
//Send the message
$numSent = $mailer->batchSend($message);
printf("Sent %d messages\n", $numSent);
/* Note that often that only the boolean equivalent of the
return value is of concern (zero indicates FALSE)
if ($mailer->batchSend($message))
{
echo "Sent\n";
}
else
{
echo "Failed\n";
}
*/