CakePHP 1.3でiso-2022-jpのメールを送る

CakePHP 2.x系はCakeEmailが利用できますが、CakePHP1.3ではUTF-8で送られてしまうので、標準で用意されているEmailを拡張して使おうかと。

【ファイル名「email_jis.php」として「app/controllers/components」に置く】
/**
 * ISO-2022-JPで送信
 * 対象バージョン: CakePHP 1.3.15
 */
App::import('Component', 'Email');
class EmailJisComponent extends EmailComponent {
function initialize(&$controller, $settings = array())
{
mb_language('ja');
$this->Controller =& $controller;
$this->charset = 'ISO-2022-JP';
$this->_set($settings);
}

function _formatAddress($string, $smtp = false)
{
$hasAlias = preg_match('/((.*))?\s?<(.+)>/', $string, $matches);
if ($smtp && $hasAlias) {
return $this->_strip('<' .  $matches[3] . '>');
} elseif ($smtp) {
return $this->_strip('<' . $string . '>');
}

if ($hasAlias && !empty($matches[2])) {
return mb_encode_mimeheader(trim($matches[2])) . $this->_strip(' <' . $matches[3] . '>');
}
return $this->_strip($string);
}

function _mail()
{
$header = implode($this->lineFeed, $this->__header);
$message = implode($this->lineFeed, $this->__message);
if (is_array($this->to)) {
$to = implode(', ', array_map(array($this, '_formatAddress'), $this->to));
} else {
$to = $this->_formatAddress($this->to);
}
if (ini_get('safe_mode')) {
return @mb_send_mail($to, $this->subject, $message, $header);
}
return @mb_send_mail($to, $this->subject, $message, $header, $this->additionalParams);
}
}

使い方(指定方法)は標準と同じですが、拡張しているのでEmailの部分をEmailJisに差し替えて利用してください。

【コントローラー内】
public $components = array('EmailJis'); //利用を宣言

$this->EmailJis->to = '名前 <account@mail.address>';
$this->EmailJis->subject = '件名';
$this->EmailJis->send('本文');

この記事へのコメント


この記事へのトラックバック