php通过smtp发送邮件的代码
刘力瑞 / 2015-10-13 / 电脑技术 / 阅读量 174

有些主机提供商不支持mail函数,发送邮件的问题一直没解决。下面是我发现的一个可行的方法,分享给大家~
mail.php文件源码:

<?php
function send_mail($to, $subject = 'No subject', $body) {
$loc_host = "刘力瑞的博客"; //名称,随意
$smtp_acc = "admin@liulirui.com"; //邮箱地址
$smtp_pass="******"; //邮箱密码
$smtp_host="smtp.exmail.qq.com"; //SMTP,此处我写的是腾讯企业的SMTP
$from="admin@liulirui.com"; //来自地址
$headers = "Content-Type: text/plain; charset=\"utf-8\"\r\nContent-Transfer-Encoding: base64";
$lb="\r\n";

$hdr = explode($lb,$headers);
if($body) {
$bdy = preg_replace("/^\./","..",explode($lb,$body));
}

$smtp = array(
array("EHLO ".$loc_host.$lb,"220,250","HELO error: "),
array("AUTH LOGIN".$lb,"334","AUTH error:"),
array(base64_encode($smtp_acc).$lb,"334","AUTHENTIFICATION error : "),
array(base64_encode($smtp_pass).$lb,"235","AUTHENTIFICATION error : ")
);
$smtp[] = array("MAIL FROM: &lt;".$from."&gt;".$lb,"250","MAIL FROM error: ");
$smtp[] = array("RCPT TO: &lt;".$to."&gt;".$lb,"250","RCPT TO error: ");
$smtp[] = array("DATA".$lb,"354","DATA error: ");
$smtp[] = array("From: ".$from.$lb,"","");
$smtp[] = array("To: ".$to.$lb,"","");
$smtp[] = array("Subject: ".$subject.$lb,"","");
foreach($hdr as $h) {$smtp[] = array($h.$lb,"","");}
$smtp[] = array($lb,"","");
if($bdy) {foreach($bdy as $b) {$smtp[] = array(base64_encode($b.$lb).$lb,"","");}}
$smtp[] = array(".".$lb,"250","DATA(end)error: ");
$smtp[] = array("QUIT".$lb,"221","QUIT error: ");

$fp = @fsockopen($smtp_host, 25);
if (!$fp) echo "Error: Cannot conect to ".$smtp_host."";
while($result = @fgets($fp, 1024)){
if(substr($result,3,1) == " ") { break; }
}

$result_str="";
foreach($smtp as $req){
@fputs($fp, $req[0]);
if($req[1]){
while($result = @fgets($fp, 1024)){
if(substr($result,3,1) == " ") { break; }
};
if (!strstr($req[1],substr($result,0,3))){
$result_str.=$req[2].$result."";
}
}
}
@fclose($fp);
return 1;
}
?>

在需要的php文件前include_once;然后用send_mail("发送地址","主题","内容")函数引用就可以了!

1 + 3 =
快来做第一个评论的人吧~