Current Location: Home> Latest Articles> How to Fix Garbled Text When Using mb_send_mail? Practical Methods to Avoid It

How to Fix Garbled Text When Using mb_send_mail? Practical Methods to Avoid It

gitbox 2025-09-04
<span><span><span class="hljs-meta"><?php</span></span><span>
</span><span><span class="hljs-comment">// This is the PHP section before the article, unrelated to the main content</span></span><span>
</span><span><span class="hljs-keyword">echo</span></span><span> </span><span><span class="hljs-string">"This article is automatically generated by PHP.\n"</span></span><span>;
</span><span><span class="hljs-meta">?></span></span><span>
<p><hr></p>
<p><h1>How to Fix Garbled Text When Using mb_send_mail? Practical Methods to Avoid It</h1></p>
<p><p>When using PHP's <code>mb_send_mail

3. Correctly Set Email Headers

Email headers are key to avoiding garbled text, especially the Content-Type and Subject encoding. For Chinese subjects, it is recommended to use mb_encode_mimeheader:

</span><span><span>$subject</span></span><span> = </span><span><span>"Test Email"</span></span><span>;
</span><span><span>$encoded_subject</span></span><span> = </span><span><span class="function_ invoke__">mb_encode_mimeheader</span></span><span>(</span><span><span>$subject</span></span><span>, </span><span><span>"UTF-8"</span></span><span>);

Then use this encoded subject in mb_send_mail:

</span><span><span class="function_ invoke__">mb_send_mail</span></span><span>(</span><span><span>$to</span></span><span>, </span><span><span>$encoded_subject</span></span><span>, </span><span><span>$message</span></span><span>, </span><span><span>$headers</span></span><span>);

4. HTML Emails and Attachments

If sending HTML emails, change the Content-Type to text/html:

</span><span><span>$headers</span></span><span> .= </span><span><span>"Content-Type: text/html; charset=UTF-8\r\n"</span></span><span>;

When sending attachments, pay extra attention to MIME boundaries and encoding methods; otherwise, attachment names or content may become garbled.

5. Common Precautions

  • Ensure the PHP script file itself is UTF-8 encoded without BOM.
  • Avoid mixing multiple character sets in the email content.
  • If using third-party libraries (like PHPMailer), they usually handle encoding automatically, which is more reliable.

Conclusion

By following these three steps, you can effectively prevent garbled text when sending emails with mb_send_mail:

  1. Set the correct internal encoding with mb_internal_encoding("UTF-8").
  2. Specify the charset in email headers with charset=UTF-8.
  3. Encode Chinese subjects using mb_encode_mimeheader.

Once you master these methods, you can confidently send Chinese emails without worrying about garbled text.

<?php // PHP section at the end of the article, unrelated to main content echo "Article generation completed."; ?>