Batch Send Email with SwiftMailer
Asked Answered
F

1

6

I'm currently using SwiftMailer to send out emails to several users (up to 50). I have it set up and working properly, however, I'm not quite sure how to pull the recipients from my MySQL database and iterate to send them.

Here is what I currently have:

<?php  
require_once 'swift/lib/swift_required.php';
$mailer = Swift_Mailer::newInstance(
Swift_SmtpTransport::newInstance('smtp.connection.com', 25)  
->setUsername('myUserName')
->setPassword('myPassword')
 );

 $mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(9));

 $message = Swift_Message::newInstance()

  ->setSubject('Let\'s get together today.')

  ->setFrom(array('[email protected]' => 'From Me'))

  ->setTo(array('[email protected]' => 'Tom Jones', '[email protected]' => 'Jane Smith', '[email protected]' => 'John Doe', '[email protected]' => 'Bill Watson',))

  ->setBody('Here is the message itself')
  ->addPart('<b>Test message being sent!!</b>', 'text/html')
   ;

  $numSent = $mailer->batchSend($message, $failures);

  printf("Sent %d messages\n", $numSent);

As you can see above, in the setTo, I'd like to iterate from my users in the database. Something like:

SELECT first, last, email FROM users WHERE is_active=1

The documentation states:

Note: Multiple calls to setTo() will not add new recipients – each call overrides the previous calls. If you want to iteratively add recipients, use the addTo() method.

But, I'm not sure: 1: How to select from my datebase in this script and: 2: If I would need to use the addTo() method in my case. Any suggestions on how to set this up properly?

Thanks!

Fannie answered 28/10, 2009 at 23:44 Comment(0)
C
7

I am not quite sure that I got your question right, but here is a way of doing it:

<?php
$message = Swift_Message::newInstance()
  ->setSubject('Let\'s get together today.')
  ->setFrom(array('[email protected]' => 'From Me'))
  ->setBody('Here is the message itself')
  ->addPart('<b>Test message being sent!!</b>', 'text/html')
;

$data = mysql_query('SELECT first, last, email FROM users WHERE is_active=1') or die(mysql_error());
while($row = mysql_fetch_assoc($data))
{
   $message->addTo($row['email'], $row['first'] . ' ' . $row['last']);
}

$message->batchSend();
?>

I hope that's what you wanted.

Calkins answered 29/10, 2009 at 0:28 Comment(1)
batchSend has been removed in the latest version of SwiftMailer. See swiftmailer.org/docs/sending.html#sending-emails-in-batch for the current documentation for sending batches of emails.Idiot

© 2022 - 2024 — McMap. All rights reserved.