代码之家  ›  专栏  ›  技术社区  ›  Dodinas

使用Swiftmailer批量发送电子邮件

  •  6
  • Dodinas  · 技术社区  · 16 年前

    我正在使用 SwiftMailer 向多个用户发送电子邮件(最多50个)。我已经设置好了,并且工作正常,但是,我不太确定如何从我的MySQL数据库中提取收件人并迭代发送它们。

    以下是我目前拥有的:

    <?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('myfrom@domain.com' => 'From Me'))
    
      ->setTo(array('tom_jones@domain.com' => 'Tom Jones', 'jsmith@domain.com' => 'Jane Smith', 'j_doe@domain.com' => 'John Doe', 'bill_watson@domain.com' => '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);
    

    正如您在上面看到的,在seto中,我想从数据库中的用户那里迭代。类似:

    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: 如何在此脚本中从我的数据库中选择,以及: 2.第2部分: 如果我需要在本例中使用addto()方法。有什么关于如何正确设置的建议吗?

    谢谢!

    1 回复  |  直到 15 年前
        1
  •  7
  •   phidah    16 年前

    我不太确定你的问题是否正确,但我可以这样做:

    <?php
    $message = Swift_Message::newInstance()
      ->setSubject('Let\'s get together today.')
      ->setFrom(array('myfrom@domain.com' => '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();
    ?>
    

    我希望这就是你想要的。

    推荐文章