Laravelのメール送信で文字化けと対決したのでその記録。
Swift Mailer
Laravelではメール送信ライブラリを標準で内包しています。使われているのは、Swift Mailer. Symfonyと同じ。
一般的な書き方
通常、以下の様なコードを書きます。
Mail::send('emails.test', $data, function($message)
{
$message->to('kaneko@example.com')
->subject('メール送信のてすと!');
});
インターネットで習った方法でおくってみた。
Mail::send('emails.test', $data, function($message)
{
$message->to('kaneko@example.com')
->subject('メール送信のてすと!')
->setCharset('iso-2022-jp')
->setEncoder(new \Swift_Mime_ContentEncoder_PlainContentEncoder('7bit'));
});
ここでちょっと文字コード変換したり、他のヘッダつけたりと試行錯誤したのですが、どうにも上手くいかなくてSwiftMailerのソースを読むことに。
vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/MimePart.php
/** Encode charset when charset is not utf-8 */
protected function _convertString($string) {
$charset = strtolower($this->getCharset());
if (!in_array($charset, array('utf-8', 'iso-8859-1', ''))) {
// mb_convert_encoding must be the first one to check,
// since iconv cannot convert some words.
if (function_exists('mb_convert_encoding')) {
$string = mb_convert_encoding($string, 'utf-8', $charset);
} elseif (function_exists('iconv')) {
$string = iconv($charset, 'utf-8//TRANSLIT//IGNORE', $string);
} else {
throw new Swift_SwiftException('/**/');
}
return $string;
}
return $string;
}
!!!!
UTF-8以外の場合、UTF-8に変換してる!
ちょっと試しに・・・
/** Encode charset when charset is not utf-8 */
protected function _convertString($string) {
$string = mb_convert_encoding($string, 'iso-2022-jp', 'utf-8');
$charset = strtolower($this->getCharset());
if (!in_array($charset, array('utf-8', 'iso-8859-1', 'iso-2022-jp'))) {
// mb_convert_encoding must be the first one to check,
// since iconv cannot convert some words.
if (function_exists('mb_convert_encoding')) {
$string = mb_convert_encoding($string, 'utf-8', $charset);
} elseif (function_exists('iconv')) {
$string = iconv($charset, 'utf-8//TRANSLIT//IGNORE', $string);
} else {
throw new Swift_SwiftException('/**/');
}
return $string;
}
return $string;
}
ただこの方法だとSwiftMailterがvendorフォルダにあるので配布するときに対象にならないという・・・
メールもUTF-8で送る時代てことでそろそろいいんじゃないですかねー
かねこ








