·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> php网站开发 >> php群发邮件,用数据库做邮件队列

php群发邮件,用数据库做邮件队列

作者:佚名      php网站开发编辑:admin      更新时间:2022-07-23
php群发邮件,用数据库做邮件队列重思想,方法自己又写的,不能保证原文的都正确...TutorialTutorial – A tutorial for Mail_QueueMail_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

<?phprequire_once"Mail/Queue.php";//optionsforstoringthemessages//typeisthecontainerused,currentlythereare'creole','db','mdb'and'mdb2'available$db_options['type']='mdb2';//theothersaretheoptionsfortheusedcontainer//herearesomefordb$db_options['dsn']='mysql://user:passWord@host/database';$db_options['mail_table']='mail_queue';//herearetheoptionsforsendingthemessagesthemselves//thesearetheoptionsneededfortheMail-Class,especiallyusedforMail::factory()$mail_options['driver']='smtp';$mail_options['host']='your_server_smtp.com';$mail_options['port']=25;$mail_options['localhost']='localhost';//optionalMail_smtpparameter$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

<?phpinclude'./config.php';/*weusethedb_optionsandmail_optionshere*/$mail_queue=&newMail_Queue($db_options,$mail_options);$from='[email protected]';$to="[email protected]";$message='Hi!Thisistestmessage!!:)';$hdrs=array('From'=>$from,'To'=>$to,'Subject'=>"testmessagebody");/*weuseMail_mime()toconstructavalidmail*/$mime=&newMail_mime();$mime->setTXTBody($message);$body=$mime->get();//the2ndparameterallowstheheadertobeoverwritten//@seehttp://pear.php.net/bugs/18256$hdrs=$mime->headers($hdrs,true);/*Putmessagetoqueue*/$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 checkdocs 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 runsa script to send the messages.Here is a simple script to achieve this:

send_messages.php

<?phpinclude'./config.php';/*Howmanymailscouldwesendeachtimethescriptiscalled*/$max_amount_mails=50;/*weusethedb_optionsandmail_optionsfromtheconfigagain*/$mail_queue=&newMail_Queue($db_options,$mail_options);/*reallysendingthemessages*/$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 sizeof 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//settheinternalbuffersizeaccordingyour//memoryresources(thenumberindicateshow//manyemailscanstayinthebufferatany//giventime)$mail_queue->setBufferSize(20);//setthequeuesize(i.e.thenumberofmailstosend)$limit=50;$mail_queue->container->setOption($limit);//loopthroughthestoredemailsandsendthemwhile($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');functionmailqueue_callback($args){$row=get_mail_queue_row($args['id']);$headers=unserialize($row['headers']);$subject=$headers['Subject'];$body=unserialize($row['body']);$mail_headers='';foreach($headersas$key=>$value){$mail_headers.="$key:$value\n";}$mail=$mail_headers."\n".$body;$decoder=newMail_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'));}?>(摘自http://pear.php.net/manual/en/package.mail.mail-queue.mail-queue.tutorial.php)