闲话不再说了,直接上代码,相信都能看懂的。
// 对邮件地址进行中文的UTF-8编码转化 function format_mail_address($address){ if(preg_match("|<([^<]+)>|", $address, $matches)){ $name = mb_substr($address, 0, strpos($address, '<')); $name = trim($name); $mail = $matches[1]; $address = "=?UTF-8?B?".base64_encode($name)."?= " . "<$mail>"; } return $address; } // 发送html格式的邮件 function html_mail($from, $to, $subject, $body){ if(preg_match("|<([^<]+)>|", $from, $matches)){ $from_name = mb_substr($from, 0, strpos($from, '<')); $from_mail = $matches[1]; $from = "=?UTF-8?B?".base64_encode($from_name)."?= " . "<$from_mail>"; }else{ $from_mail = $from; } $headers[] = "From: $from"; $headers[] = "X-Mailer: PHP"; $headers[] = "MIME-Version: 1.0"; $headers[] = "Content-type: text/html; charset=utf8"; $headers[] = "Reply-To: $from_mail"; $subject = "=?UTF-8?B?".base64_encode($subject)."?="; if(is_array($to)){ foreach($to as $mail) $to_mails[] = format_mail_address($mail); $to = join(", ", $to_mails); } mail($to, $subject, $body, join("\r\n", $headers), "-f $from_mail"); }
函数使用可以参照下面的例子:
html_mail( "老谷自言自语 <[email protected]>", array( "用户A <[email protected]>", "用户B <[email protected]>"), "这是一封测试邮件", "<html><body><h1 style='color:red'> 感谢党,感谢政府,感谢大中华局域网,给我这个发送邮件的机会。 </h1></body></html>" );
PHP mail函数调用sendmail发送邮件,请尽量在linux系统中尝试以上代码
注意:以上代码运行可能存在国内邮箱中收不到的情况,因为可能包含敏感词汇。
如我的测试中,gmail收到邮件并置于垃圾邮箱中,而163没有收到。