LoginSignup
40
39

More than 5 years have passed since last update.

メール本文が一行1000バイトを超えると文字化ける問題

Last updated at Posted at 2016-02-18

sendmail、qmail、Postfixで送信するメールで一行あたり1000バイトを超えると、自動で改行コードが挿入される問題。
マルチバイト文字列とか全然考慮されないまま改行コードが挿入されるらしく、それが原因で日本語が文字化けてしまう。
上記のMTAに限らずどのMTAでもだいたいそういう仕様になってるっぽい。

RFCのドキュメントにも、一行1000バイト超えたメール本文を作っちゃだめだよーって明記されている。
ので、おとなしくアプリケーション側で長い行に対して改行文字を差し込む。

以下、長い行に改行文字を入れるPHPのメソッド書いた。

function _preventGarbledCharacters($bigText, $width=249) {
    // wordwrap()はマルチバイト未対応のため正規表現を使う。
    $pattern = "/(.{1,{$width}})(?:\\s|$)|(.{{$width}})/uS";
    $replace = '$1$2' . "\n";
    $wrappedText = preg_replace($pattern, $replace, $bigText);
    return $wrappedText;
}

これで強制改行が原因の文字化けは無くなるはず。

参考

http://srgia.com/docs/rfc2822j.html#p2.1.1
http://www.geek.sc/archives/743
https://siiz.biz/memo/detail.php?id=70

40
39
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
39