Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch Send Email with SwiftMailer

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!

like image 310
Dodinas Avatar asked Oct 28 '09 23:10

Dodinas


1 Answers

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.

like image 188
phidah Avatar answered Sep 20 '22 18:09

phidah