IsSMTP(); // 设置使用SMTP服务发送 $mail->Host = "smtp.mail.com"; $mail->Username = "user">
当前位置:Gxlcms > PHP教程 > PHPMailer邮件标题中文乱码的解决方法

PHPMailer邮件标题中文乱码的解决方法

时间:2021-07-01 10:21:17 帮助过:30人阅读

  1. /**

  2. * PHPMailer邮件发送
  3. * Edit bbs.it-home.org
  4. */
  5. function smtp_main_send( $to, $subject, $message, $from, $fromName )
  6. {
  7. $mail = new PHPMailer();

  8. $mail->CharSet = "UTF-8"; // 设置编码

  9. $mail->IsSMTP(); // 设置使用SMTP服务发送

  10. $mail->Host = "smtp.mail.com";
  11. $mail->Username = "user";
  12. $mail->Password = "pass";
  13. $mail->SMTPAuth = true;

  14. $mail->From = $from;

  15. $mail->FromName = $fromName;

  16. if ( is_array( $to ) ) {

  17. foreach ( $to as $address ) {
  18. $mail->AddAddress( $address );
  19. }
  20. } else {
  21. $mail->AddAddress( $to );
  22. }

  23. $mail->Subject = $subject;

  24. $mail->Body = $message;
  25. $mail->AltBody = $message;
  26. $mail->IsHTML( true );

  27. return $mail->Send();

  28. }
  29. ?>

用以上的代码发送英文邮件没有问题,但发送中文邮件时标题会有乱码。

解决方法: 需要对 class.phpmailer.php 做一些修改:

修改1,1137 行: function EncodeHeader ($str, $position = 'text') {

将函数增加一个参数:

  1. function EncodeHeader ($str, $position = 'text', $pl = 0) {
  2. if ( $pl ) return "=?" . $this->CharSet . "?B?" . base64_encode($str) . "?=";

修改2,796 行: $result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject)));

将调用改为:

  1. $result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject),'text', 1));

即可解决中文标题乱码的问题。

附,PHPMailer邮件发送类V5.1下载地址。

人气教程排行