其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

php+mysql 模拟发送邮件队列

GG网络技术分享 2025-03-18 16:17 0


Image

如果使用阿里云邮箱发送文件,邮箱内容先到阿里云服务器,然后阿里云服务器在转发给新浪服务器,新浪服务器在转发给用户。

telnet模拟邮件发送

准备工作:

1)2个邮箱,建议用sina和aliyun邮箱
2)确保telnet命令被允许使用

cmd命令行下:使用telnet工具连上某个邮箱服务的smtp服务器,如aliyun(阿里云):
telnet smtp.aliyun.com 25

利用phpmailer类实现邮件发送

phpmailer 下载地址:https://github.com/PHPMailer/PHPMailer/

//获取邮件设置信息

$email_host = getConfigValue(\'email_host\');

$email_title = getConfigValue(\'email_title\');

$email_name = getConfigValue(\'email_name\');

$email_user = getConfigValue(\'email_user\');

$email_password = getConfigValue(\'email_password\');

Vendor(\'PHPMailer.class#phpmailer\');

//实例化PHPMailer类,true表示出现错误时抛出异常

$mail = new \\PHPMailer();

// 使用SMTP

try{

$mail->IsSMTP();

$mail->Host = \"smtp.aliyun.com\"; // SMTP server

$mail->SMTPAuth = true; // 服务器需要验证

$mail->CharSet =\"UTF-8\"; //设定邮件编码

$mail->Username = $email_user; //SMTP服务器的用户帐号

$mail->Password = $email_password; //SMTP服务器的用户密码

//$mail->Port = 25; // 设置端口,使用默认就可以

// $mail->SMTPDebug = 1; // 启用SMTP调试 1 = errors 2 = messages

$mail->SetFrom(\"chenruiqiang@yd-x.com\",\"gather\"); //发件人

if (is_array($tomail)){

foreach ($tomail as $m){

$mail->AddAddress(\"liushuyu@yd-x.com\", \'liushuyu\'); //收件人

}

}else{

$mail->AddAddress($tomail, \'user\');

}

$mail->Subject = $title; //邮件主题

$mail->AddReplyTo($email_name,$email_title); //收件人回复时回复到此邮箱,可以多次执行该方法

if($file != \'\' OR $file != NULL){

$rootpath = $_SERVER[\'DOCUMENT_ROOT\'];

$filepath = $rootpath.$file;

$mail->AddAttachment($filepath,$filename); // 添加附件,并指定名称

}

$mail->Body = $content; //以下是邮件内容相关

$mail->IsHTML(true); //主题是否包含html内容

$mail->Send();

return true;

}catch (Exception $e){

return false;

}

为什么需要队列

我们需要给网站所有用户发送一封系统通知邮件,假设网站有10000个注册用户,发送没封邮件需要0.1秒,执行一次发送通知操作需要多长时间?
10000 X 0.1 = 1000秒 = 16(分)
使用队列先到先发送
使用phpcli 模式。
php cli模式不依靠apache

$count = 0;

while(true){

$count ++ ;

echo $count.\'\\r\\n\';

if($count >= 10){

break;

}

sleep(3);停止3秒

echo \'done\'

}

1)触发队列
exec函数触发cli模式
exec(\'php.exe文件绝对路径 cli_test.php\',)
注意:为了能保持在后台运行,此程序必须将输出重定向到文件或其它输出流。否则会导致 PHP 挂起,直至程序执行结束。

<?php

function execInBackground($cmd) {

if (substr(php_uname(), 0, 7) == \"Windows\"){

pclose(popen(\"start /B \". $cmd, \"r\"));

}

else {

exec($cmd . \" > /dev/null &\");

}

}

?>

在phpcli模式下测试队列

//判断队列进程是否在执行

public function testCmd(){

exec(\"ps aux | grep /hphc.yd-x.com/Public/mysql/quene_recommand.php\",$output,$returnvalue);

if(count($output) == 3 && $returnvalue == 0){

return true;

}else{

echo \'0\';

return false;

}

}

Ajax异步触发队列

使用jquery Ajax 出发队列操作

标签: 队列 服务器

提交需求或反馈

Demand feedback