Home » Mail » Mail_Queue » Manual
Class Summary Mail_Queue
Class Summary Mail_Queue – Mail_Queue - base class for mail queue managment.
Mail_Queue - base class for mail queue managment.
This class allows you to queue mails for later delivery.
Class Trees for Mail_Queue
- Pear
- Mail_Queue
Tutorial
Tutorial – A tutorial for Mail_Queue
Mail_Queue usage with a simple example
We are using the db-container for the example and a mysql database. You need to create some tables in the mysql-database to store the messages:
mysql.sql
CREATE TABLE mail_queue ( id bigint(20) NOT NULL default '0', create_time datetime NOT NULL default '0000-00-00 00:00:00', time_to_send datetime NOT NULL default '0000-00-00 00:00:00', sent_time datetime default NULL, id_user bigint(20) NOT NULL default '0', ip varchar(20) NOT NULL default 'unknown', sender varchar(50) NOT NULL default '', recipient text NOT NULL, headers text NOT NULL, body longtext NOT NULL, try_sent tinyint(4) NOT NULL default '0', delete_after_send tinyint(1) NOT NULL default '1', PRIMARY KEY (id), KEY id (id), KEY time_to_send (time_to_send), KEY id_user (id_user) );
First you need to define some options. As you need them two times (once for adding messages, once for sending the messages) its always good to add them to a config-file. Let's call it config.php
config.php
<?php
require_once "Mail/Queue.php";
// options for storing the messages
// type is the container used, currently there are 'creole', 'db', 'mdb' and 'mdb2' available
$db_options['type'] = 'mdb2';
// the others are the options for the used container
// here are some for db
$db_options['dsn'] = 'mysql://user:password@host/database';
$db_options['mail_table'] = 'mail_queue';
// here are the options for sending the messages themselves
// these are the options needed for the Mail-Class, especially used for Mail::factory()
$mail_options['driver'] = 'smtp';
$mail_options['host'] = 'your_server_smtp.com';
$mail_options['port'] = 25;
$mail_options['localhost'] = 'localhost'; //optional Mail_smtp parameter
$mail_options['auth'] = false;
$mail_options['username'] = '';
$mail_options['password'] = '';
?>
So we are done configuring it, now let's use it. First we need to construct a mail-message and add it to the queue:
add_message.php
<?php
include './config.php';
/* we use the db_options and mail_options here */
$mail_queue =& new Mail_Queue($db_options, $mail_options);
$from = 'user@server.com';
$to = "user2@server.com";
$message = 'Hi! This is test message!! :)';
$hdrs = array( 'From' => $from,
'To' => $to,
'Subject' => "test message body" );
/* we use Mail_mime() to construct a valid mail */
$mime =& new Mail_mime();
$mime->setTXTBody($message);
$body = $mime->get();
// the 2nd parameter allows the header to be overwritten
// @see http://pear.php.net/bugs/18256
$hdrs = $mime->headers($hdrs, true);
/* Put message to queue */
$mail_queue->put($from, $to, $hdrs, $body);
?>
NB: the first time you call put(), PEAR::DB and PEAR::MDB2 will create a new table to keep the sequence number, so make sure the db user you are using has "CREATE TABLE" privileges. Or you can create the table separately, calling the createSequence() method of PEAR::DB or PEAR::MDB2 (you should also be aware that the two DBAL will create a table with a different field name: "id" for DB, "sequence" for MDB2).
Ok, now we've used the simple way to add a message ... there are more advanced options, please check docs of the put-function for these. Now we need to send the messages. This is most often done by using a cron-job which regularly runs a script to send the messages. Here is a simple script to achieve this:
send_messages.php
<?php
include './config.php';
/* How many mails could we send each time the script is called */
$max_amount_mails = 50;
/* we use the db_options and mail_options from the config again */
$mail_queue =& new Mail_Queue($db_options, $mail_options);
/* really sending the messages */
$mail_queue->sendMailsInQueue($max_amount_mails);
?>
We are done. Now run the last script regularly and add your mails to the queue as needed.
Since Mail_Queue v.1.1, the preload() method doesn't preload ALL the mails in memory, but just a few of them each time. When the buffer is empty, it is filled again automatically. You can set the size of the buffer via the new setBufferSize() method.
You can also send the stored emails one by one. Here is a simple script to achieve this:
send_messages_one_by_one.php
<?php
// set the internal buffer size according your
// memory resources (the number indicates how
// many emails can stay in the buffer at any
// given time)
$mail_queue->setBufferSize(20);
//set the queue size (i.e. the number of mails to send)
$limit = 50;
$mail_queue->container->setOption($limit);
// loop through the stored emails and send them
while ($mail = $mail_queue->get()) {
$result = $mail_queue->sendMail($mail);
}
?>
Utilising Callbacks for Report Generation
The sendMailsInQueue method, since version 1.2.3, has callback support. This may be utilised for report generation and postprocessing.
The callback function is called before the relevant entry is deleted from the mail_queue table in the database so if necessary you could add extra fields to it for inserting into your log/report table. The function should accept only one parameter - an associative array of values; 'id', 'queued_as' and 'greeting'.
You'll need to use recent releases of the PEAR::Mail (version 1.2.0b3 or higher) and PEAR::Net_SMTP (version 1.3.3 or higher) packages to be able to retrieve the esmtp id and greeting details if you need them for your reports. Also, if you want to decode the body of the email and store that for your report you'll need to install the PEAR::Mail_mimeDecode package.
Provide the callback function like so:
<?php
$returned = $mail_queue->sendMailsInQueue(
MAILQUEUE_ALL,
MAILQUEUE_START,
MAILQUEUE_TRY,
'mailqueue_callback');
function mailqueue_callback($args) {
$row = get_mail_queue_row($args['id']);
$headers = unserialize($row['headers']);
$subject = $headers['Subject'];
$body = unserialize($row['body']);
$mail_headers = '';
foreach($headers as $key=>$value) {
$mail_headers .= "$key:$value\n";
}
$mail = $mail_headers . "\n" . $body;
$decoder = new Mail_mimeDecode($mail);
$decoded = $decoder->decode(array(
'include_bodies' => TRUE,
'decode_bodies' => TRUE,
'decode_headers' => TRUE,
));
$body = $decoded->body;
$esmtp_id = $args['queued_as'];
if (isset($args['greeting'])) {
$greeting = $args['greeting'];
$greets = explode(' ', $greeting);
$server = $greets[0];
} else {
$server = 'localhost';
}
insert_to_log(compact('server', 'esmtp_id', 'subject', 'body'));
}
?>
constructor Mail_Queue::Mail_Queue
constructor Mail_Queue::Mail_Queue() – Mail_Queue constructor
Synopsis
require_once 'Mail/Queue.php';
mixed constructor Mail_Queue::Mail_Queue (
array $container_options
, array $mail_options
)
Description
Creates a new mail queue object to store mails in, fetch mails from and send mails with.
Parameter
-
array
$container_options -
Array of container (mail storage) options. See tutorial for details.
-
array
$mail_options -
Array of mailer options. See tutorial for details.
<?php
require_once 'Mail/Queue.php';
$container_options = array(
'type' => 'db',
'database' => 'dbname',
'phptype' => 'mysql',
'username' => 'root',
'password' => '',
'mail_table' => 'mail_queue',
);
//optionally, a 'dns' string can be provided instead of db parameters.
//look at DB::connect() method or at DB or MDB docs for details.
//you could also use mdb container instead db
$mail_options = array(
'driver' => 'smtp',
'host' => 'your_smtp_server.com',
'port' => 25,
'auth' => false,
'username' => '',
'password' => '',
);
$mail_queue =& new Mail_Queue($container_options, $mail_options);
* *****************************************************************
* // TO ADD AN EMAIL TO THE QUEUE
* *****************************************************************
$from = 'user@server.com';
$from_name = 'admin';
$recipient = 'recipient@other_server.com';
$recipient_name = 'recipient';
$message = 'Test message';
$from_params = empty($from_name) ? '<'.$from.'>' : '"'.$from_name.'" <'.$from.'>';
$recipient_params = empty($recipient_name) ? '<'.$recipient.'>' : '"'.$recipient_name.'" <'.$recipient.'>';
$hdrs = array(
'From' => $from_params,
'To' => $recipient_params,
'Subject' => 'test message body',
);
$mime =& new Mail_mime();
$mime->setTXTBody($message);
$body = $mime->get();
$hdrs = $mime->headers($hdrs);
// Put message to queue
$mail_queue->put($from, $recipient, $hdrs, $body);
// Also you could put this msg in more advanced mode
$seconds_to_send = 3600;
$delete_after_send = false;
$id_user = 7;
$mail_queue->put( $from, $recipient, $hdrs, $body, $seconds_to_send, $delete_after_send, $id_user );
// TO SEND EMAILS IN THE QUEUE
// How many mails could we send each time
$max_ammount_mails = 50;
$mail_queue =& new Mail_Queue($container_options, $mail_options);
$mail_queue->sendMailsInQueue($max_ammount_mails);
?>
Return value
returnsTrue on success else pear error class.
Throws
throws no exceptions thrown
Note
This function can not be called statically.
Mail_Queue::deleteMail
Mail_Queue::deleteMail() – Delete a mail from queue.
Synopsis
require_once 'Mail/Queue.php';
boolean Mail_Queue::deleteMail (
integer $id
)
Description
Deletes a mail from the queue by identifier.
Parameter
-
integer
$id -
Mail identifier.
Throws
throws no exceptions thrown
Note
This function can not be called statically.
Mail_Queue::factorySendMail
Mail_Queue::factorySendMail() – Creates the necessary Mail object.
Synopsis
require_once 'Mail/Queue.php';
void Mail_Queue::factorySendMail (
)
Description
Creates the necessary Mail object.
Throws
throws no exceptions thrown
Note
This function can not be called statically.
Mail_Queue::get
Mail_Queue::get() – Get next mail from queue.
Synopsis
require_once 'Mail/Queue.php';
object Mail_Queue_Container::get (
)
Description
Get next mail from queue. The emails are preloaded into an internal memory buffer to speed up the process. Since Mail_Queue v.1.1, the preload() method doesn't preload ALL the mails in memory, but just a few of them each time. When the buffer is empty, it is filled again automatically. You can set the size of the buffer via the setBufferSize() method.
Return value
returnsMail_Queue_Body object
Throws
throws no exceptions thrown
Note
This function can not be called statically.
Mail_Queue::put
Mail_Queue::put() – Put a new mail into queue.
Synopsis
require_once 'Mail/Queue.php';
int Mail_Queue::put (
string $from
, string $to
, array $hdrs
, array $body
, integer $sec_to_send = 0
, bool $delete_after_send
= true
, integer $id_user = MAILQUEUE_SYSTEM
)
Description
Injects a new mail into the mail queue.
Parameter
-
string
$from -
Sender e-mail address.
-
string
$to -
Recipient e-mail address.
-
array
$hdrs -
Array of mail headers as returned by Mail_Mime::headers().
-
array
$body -
Mail body array as returned by Mail_Mime::get().
-
mixed
$sec_to_send -
Optional - Seconds to pass before delivery is attempted.
-
mixed
$delete_after_send -
Optional - Whether or not to delete the mail after delivery.
-
integer
$id_user -
Optional - user ID. Stored in queue and readable from mail body object with getIdUser() at a later point.
Return value
returns ID of the record where this mail has been put or Mail_Queue_Error on error
Throws
throws no exceptions thrown
Note
This function can not be called statically.
Mail_Queue::sendMail
Mail_Queue::sendMail() – Sends mail object returned by Mail_Queue::get()
Synopsis
require_once 'Mail/Queue.php';
mixed Mail_Queue::sendMail (
object MailBody $mail
)
Description
Sends mail object returned by Mail_Queue::get().
Parameter
-
object MailBody
$mail -
Mail object.
Return value
returns True on success else pear error class
Throws
throws no exceptions thrown
Note
This function can not be called statically.
Mail_Queue::sendMailById
Mail_Queue::sendMailById() – Send a specific mail.
Synopsis
require_once 'Mail/Queue.php';
bool Mail_Queue::sendMailById (
integer $id
)
Description
Sends a single mail from the queue specified by $id. Note: The queue entry will not be deleted automatically after delivery!
Parameter
-
integer
$id -
Mail identifier
Return value
returns True on success else false
Throws
throws no exceptions thrown
Note
This function can not be called statically.
Mail_Queue::sendMailsInQueue
Mail_Queue::sendMailsInQueue() – Send mails from queue.
Synopsis
require_once 'Mail/Queue.php';
mixed Mail_Queue::sendMailsInQueue (
integer $limit = MAILQUEUE_ALL
, integer $offset = MAILQUEUE_START
, integer $try = MAILQUEUE_TRY
, string or array $callback = null
)
Description
Sends mails remaining in queue.
Parameter
-
integer
$limit -
Optional - maximum number of mails to send.
-
integer
$offset -
Optional - skip $offset mails and start sending from there.
-
integer
$try -
Optional - count of tries before mail returns to queue for later delivery.
-
string
$callback -
Optional - details of callback function to be used after mail has been sent.
Return value
returnsTrue on success else Mail_Queue_Error object.
Throws
throws no exceptions thrown
Note
This function can not be called statically.