Home >Backend Development >PHP Tutorial >Solution to garbled Chinese characters in PHPMailer email title

Solution to garbled Chinese characters in PHPMailer email title

WBOY
WBOYOriginal
2016-07-25 08:59:401074browse
  1. /**

  2. * PHPMailer email sending
  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下载地址。



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn