重思想,方法自己又写的,不能保证原文的都正确...

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']      = ;
$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 = ;

/* 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();

//set the queue size (i.e. the number of mails to send)
$limit = ;
$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[];
    } 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)

php群发邮件,用数据库做邮件队列的更多相关文章

  1. Asp.Net Core 快速邮件队列设计与实现

    发送邮件几乎是软件系统中必不可少的功能,在Asp.Net Core 中我们可以使用MailKit发送邮件,MailKit发送邮件比较简单,网上有许多可以参考的文章,但是应该注意附件名长度,和附件名不能 ...

  2. laravel5.6 邮件队列database驱动简单demo

    一: 邮件初始参数配置 配置 .env  (demo示例是163邮箱,开启POP3和SMTP服务,获取授权密码) MAIL_DRIVER=smtp MAIL_HOST=smtp.163.com MAI ...

  3. Linux基础命令---mailq显示邮件队列

    mailq mailq指令可以显示出待发送的邮件队列. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora.   1.语法       mailq   2.选项参数列表 ...

  4. SQL SERVER 2008配置Database Mail –用SQL 数据库发邮件

    SQL SERVER 2008配置Database Mail –用SQL  数据库发邮件 https://blogs.msdn.microsoft.com/apgcdsd/2011/06/28/sql ...

  5. 管理 sendmail 的邮件队列

    邮件队列是存储 sendmail 命令传送的邮件消息数据和控制文件的目录.缺省情况下,邮件队列是 /var/spool/mqueue. 邮件消息可能由于很多原因而排入队列. 例如: sendmail  ...

  6. paip.数据库发邮件通知配置

    paip.数据库发邮件通知配置 作者Attilax ,  EMAIL:1466519819@qq.com  来源:attilax的专栏 地址:http://blog.csdn.net/attilax ...

  7. Confluence 6 邮件队列

    需要发送的电子邮件将会在邮件队列中进行等待,Confluence 的邮件队列每分钟刷新一次.Confluence 的管理员也可以手动的刷新邮件队列中等待发送的消息. 如果在发送的时候出现了错误,那么出 ...

  8. m_Orchestrate learning system---二十九、什么情况下用数据库做配置字段,什么情况下用配置文件做配置

    m_Orchestrate learning system---二十九.什么情况下用数据库做配置字段,什么情况下用配置文件做配置 一.总结 一句话总结: 配置文件 开发人员 重置 数据库 非开发人员 ...

  9. Postfix常用命令和邮件队列管理(queue)

    本文主要介绍一下postfix的常用命令及邮件队列的管理: Postfix有以下四种邮件队列,均由管理队列的进程统一进行管理: maildrop:本地邮件放置在maildrop中,同时也被拷贝到inc ...

随机推荐

  1. PHP storm快捷键

    左边文件路径看不到了,按alt+1就出来了 ctrl+j 插入活动代码提示 ctrl+alt+t 当前位置插入环绕代码 alt+insert 生成代码菜单 ctrl+q 查看代码注释 ctrl+d 复 ...

  2. Samba Server 配置

    1.Issue:Server requested plaintext password but 'client plaintext auth' is disabled   session setup ...

  3. javascript模板库jsrender加载并缓存外部模板文件

    前一篇说了jsrender嵌套循环的使用,在SPA的应用中,广泛使用的一个点就是view模板,使用了SPA之后,每个业务页面不再是独立的html,仅仅是一个segment,所以通常这些segment会 ...

  4. 线程(三)__Interrupt 、setDaemon()、join

    一.wait和sleep区别? 1.wait可以指定也可以不指定.sleep必须指定时间. 2.在同步中时,对cpu的执行权和锁的处理不同.它们都能将线程处于冻结状态. wait:释放执行权,释放锁. ...

  5. AngularJs学习第一课 Hello World

    首先先介绍一下:AngularJS是干什么的. AngularJS是为了克服HTML在构建应用上的不足而设计的.HTML是一门很好的为静态文本展示设计的声明式语言,但要构建WEB应用的话它就显得乏力了 ...

  6. Gremlins.js – 模拟用户随机操作的 JS 测试库

    Gremlins.js 是基于 JavaScript 编写的 Monkey 测试库,支持 Node.js 平台和浏览器中使用.Gremlins.js 随机模拟用户操作:单击窗口中的任意位置,在表格中输 ...

  7. CSS盒子模型

    2016-10-22 <css入门经典>第6章 1.每个HTML元素对应于一个显示盒子,但不是所有的元素都显示在屏幕上. 2.HTML元素显示为CSS显示盒子的真正方法称为"可视 ...

  8. 【初窥javascript奥秘之事件机制】论“点透”与“鬼点击”

    前言 最近好好的研究了一番移动设备的点击响应速度,期间不断的被自己坑,最后搞得焦头烂额,就是现在可能还有一些问题,但是过程中感觉自己成长不少, 最后居然感觉对javascript事件机制有了更好的认识 ...

  9. 【原】iOS动态性(二):运行时runtime初探(强制获取并修改私有变量,强制增加及修改私有方法等)

    OC是运行时语言,只有在程序运行时,才会去确定对象的类型,并调用类与对象相应的方法.利用runtime机制让我们可以在程序运行时动态修改类.对象中的所有属性.方法,就算是私有方法以及私有属性都是可以动 ...

  10. kali 忘记登录密码后重置的方法

    首先启动你的卡里系统,等出现引导界面时选择恢复模式.如下图: 再出来一个界面时,选择第二个并按E键进入编辑模式.如下图: 进入编辑模式后找到如下图的代码: 把ro改为rw,并且在.gz 后面写上ini ...