2009-10-28 205 views
5

我目前使用SwiftMailer發送電子郵件給幾個用戶(最多50)。我已經設置並正常工作,但是,我不太確定如何從我的MySQL數據庫中提取收件人並迭代發送它們。批量發送電子郵件與SwiftMailer

這是我目前有:

<?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); 

正如你可以在上面看到,在setTo,我想從我的數據庫中的用戶進行迭代。喜歡的東西:

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

documentation狀態:

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.

但是,我不知道:1:如何從我的DATEBASE在這個腳本選擇和:2 :如果我需要在我的情況下使用addTo()方法。有關如何正確設置的建議?

謝謝!

回答

6

我不太清楚,我得到了正確的你的問題,但在這裏是做這件事的方式:

<?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(); 
?> 

我希望這是你想要的。

+1

batchSend已在最新版本的SwiftMailer中刪除。有關發送批量電子郵件的最新文檔,請參閱http://swiftmailer.org/docs/sending.html#sending-emails-in-batch。 – DrCord 2015-01-05 18:28:18

相關問題