PHPMailer是PHP语言的优秀的邮件发送包。支持 SMTP,CC,BCC,Sendmail 等多种发送方式。
下面是一个基于 PHPMailer 的发送函数,旧代码了:
function smtp_main_send( $to, $subject, $message, $from, $fromName )
{
$mail = new PHPMailer();
$mail->CharSet = "UTF-8"; // 设置编码
$mail->IsSMTP(); // 设置使用SMTP服务发送
$mail->Host = "smtp.mail.com";
$mail->Username = "user";
$mail->Password = "pass";
$mail->SMTPAuth = true;
$mail->From = $from;
$mail->FromName = $fromName;
if ( is_array( $to ) ) {
foreach ( $to as $address ) {
$mail->AddAddress( $address );
}
} else {
$mail->AddAddress( $to );
}
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = $message;
$mail->IsHTML( true );
return $mail->Send();
}
直接这样发送邮件,英文没有问题,但在发送中文的时候标题会有乱码。需要对 class.phpmailer.php 做一些修改:
修改1,1137 行:
function EncodeHeader ($str, $position = 'text') {
将函数增加一个参数:
function EncodeHeader ($str, $position = 'text', $pl = 0) {
if ( $pl ) return "=?" . $this->CharSet . "?B?" . base64_encode($str) . "?=";
修改2,796 行:
$result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject)));
将调用改为:
$result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject),'text', 1));