LoginSignup
20
22

More than 5 years have passed since last update.

Codeigniter で日本語メールを送信するときに失敗しない方法

Last updated at Posted at 2014-11-19

やりたかったこと

Codeigniter の email ライブラリを使って、メールを送る機能を付けたかった。しかし、デフォルトのライブラリだと、 Outlook などのメーラーで件名または本文が文字化けしてしまう、という事象が生じました。ここでは、失敗しないメール送信の実装方法を紹介します。

①独自email ライブラリを作成

デフォルトのemail ライブラリにある次のコードが問題のようです。

system/libraries/email.php
$subject = $this->_prep_q_encoding($subject);

$this->_body = stripslashes(rtrim(str_replace("\r", "", $body)));

なので、email.php をコピーしてライブラリファイルを作成し、
問題の箇所だけ次のように変更します。

application/libraries/Myemail.php
public function subject($subject)
{
//$subject = $this->_prep_q_encoding($subject);
$this->_set_header('Subject', $subject);
return $this;
}

public function message($body)
{
if (strtolower($this->charset) == 'iso-2022-jp')
{
$this->_body = rtrim(str_replace("\r", "", $body));
}
else
{
//$this->_body = stripslashes(rtrim(str_replace("\r", "", $body)));
$this->_body = rtrim(str_replace("\r", "", $body));
}
return $this;
}

②エンコーディングを変換

メール送信部分は、こんな風に書きます。
ポイントは、件名と本文は mb_convert_encoding で、送信者名は mb_encode_mimeheader でエンコーディングすることです。

application/models/mail.php
    function mail_send($to,$from,$from_name,$sbj,$body){

      $this->load->library('myemail');//独自email libraryを読み出し

      //メール初期化
            $config['protocol'] = 'sendmail';
            $config['mailpath'] = '/usr/sbin/sendmail';
            $config['_encoding'] = '7bit';
            $config['charset'] = 'ISO-2022-JP';
            $config['wordwrap'] = FALSE;
            $this->myemail->initialize($config);

            $sbj = mb_convert_encoding($sbj, "ISO-2022-JP", "UTF-8,EUC-JP,auto");
            $from_name = mb_encode_mimeheader($from_name, "ISO-2022-JP", "UTF-8,EUC-JP,auto");
            $body = mb_convert_encoding($body, "ISO-2022-JP", "UTF-8,EUC-JP,auto");

            $this->myemail->from($from, $from_name);
            $this->myemail->to($to);
            $this->myemail->subject($sbj);
            $this->myemail->message($body);
            $this->myemail->send();
    }

これで一旦、文字化けはなくなるはずです!

補足:機種依存文字・半角カタカナの文字化けもなんとかしたい

以前に記事を書いたので、こちらを参照してください。

【PHP】半角カタカナがメールで文字化けしたときの対処法

【PHP】機種依存文字を変換する最低限のコード

参考サイト

20
22
0

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
20
22