Sending Multiple Mails per SMTP Connection

By default, a single SMTP transport creates a single connection and re-uses it for the lifetime of the script execution. You may send multiple e-mails through this SMTP connection. A RSET command is issued before each delivery to ensure the correct SMTP handshake is followed.

Optionally, you can also define a default From email address and name, as well as a default reply-to header. This can be done through the static methods setDefaultFrom() and setDefaultReplyTo(). These defaults will be used when you don't specify a From/Reply-to Address or -Name until the defaults are reset (cleared). Resetting the defaults can be done through the use of the clearDefaultFrom() and clearDefaultReplyTo.

Example #1 Sending Multiple Mails per SMTP Connection

  1. // Create transport
  2. $config = array('name' => 'sender.example.com');
  3. $transport = new Zend_Mail_Transport_Smtp('mail.example.com', $config);
  4.  
  5. // Set From & Reply-To address and name for all emails to send.
  6. Zend_Mail::setDefaultFrom('sender@example.com', 'John Doe');
  7. Zend_Mail::setDefaultReplyTo('replyto@example.com','Jane Doe');
  8.  
  9. // Loop through messages
  10. for ($i = 0; $i < 5; $i++) {
  11.     $mail = new Zend_Mail();
  12.     $mail->addTo('studio@example.com', 'Test');
  13.  
  14.     $mail->setSubject(
  15.         'Demonstration - Sending Multiple Mails per SMTP Connection'
  16.     );
  17.     $mail->setBodyText('...Your message here...');
  18.     $mail->send($transport);
  19. }
  20.  
  21. // Reset defaults
  22. Zend_Mail::clearDefaultFrom();
  23. Zend_Mail::clearDefaultReplyTo();

If you wish to have a separate connection for each mail delivery, you will need to create and destroy your transport before and after each send() method is called. Or alternatively, you can manipulate the connection between each delivery by accessing the transport's protocol object.

Example #2 Manually controlling the transport connection

  1. // Create transport
  2. $transport = new Zend_Mail_Transport_Smtp();
  3.  
  4. $protocol = new Zend_Mail_Protocol_Smtp('mail.example.com');
  5. $protocol->connect();
  6. $protocol->helo('sender.example.com');
  7.  
  8. $transport->setConnection($protocol);
  9.  
  10. // Loop through messages
  11. for ($i = 0; $i < 5; $i++) {
  12.     $mail = new Zend_Mail();
  13.     $mail->addTo('studio@example.com', 'Test');
  14.     $mail->setFrom('studio@example.com', 'Test');
  15.     $mail->setSubject(
  16.         'Demonstration - Sending Multiple Mails per SMTP Connection'
  17.     );
  18.     $mail->setBodyText('...Your message here...');
  19.  
  20.     // Manually control the connection
  21.     $protocol->rset();
  22.     $mail->send($transport);
  23. }
  24.  
  25. $protocol->quit();
  26. $protocol->disconnect();
blog comments powered by Disqus