チェ・ゲバムラの日記

脱犬の道を目指す男のブログ

【CakePHP2.x】CakeEmailクラスを使ったメール送信 ~CakePHP2実践入門「9章」~

メールヘッダインジェクション対策

登録フォームでメール、所属を入力してもらい、
それをそのままメールヘッダに入れるプログラムの場合。
改行コードが入ると勝手にCCアドレスも入力できちゃったりする。

通常Cake側で自動処理して欲しいところだが、
CakePHP2.2.0など古いバージョンでは自分で実装が必要。

実装方法は改行文字を削除するエスケープ処理。
ex

<?php
$organization = preg_replace("/¥r/", '' , $organization);
$organization = preg_replace("/¥n/", '' , $organization);
$email->addHeaders(array('Organization', $organization));

ファイル添付

単純な添付

<?php
$email->attachments(APP . '/webroot/img/cake.icon.png');      

その他、ファイル名変更して添付や複数ファイル添付も可能。

テンプレートを使ってHTMLメールを送信

1.レイアウトとビュー作成
View/Layouts/Emails/html/sample_layout.ctp

<!doctype html>
<html>
<head>
  <meta http-equiv="Content-Type"
        content="text/html; charset=ISO-2022-JP">
  <title>サンプルレイアウト</title>
</head>
<body>
<?php echo $this->fetch('content');?>
</body>
</html> 

View/Emails/html/thank_you.ctp

<h3><?php h($user);?>、登録ありがとうございました。</h3>                    
<a href="gihyo.jp">gihyo</a>


Controller/SampleController.php

<?php 
App::uses('CakeEmail','Network/Email');
class SampleController extends AppController{
    public function index(){
          $email = new CakeEmail(array(
                                 'charset' => 'ISO-2022-JP'
                                 ));

              $email->transport('Mail');

              $email->from('webdev@murayama.hubers.asia');
              $email->to('murayama0311@gmail.com');
              $email->subject('コレはテストメールです');

              $email->attachments(APP . '/webroot/img/cake.icon.png');

              $email->template('thank_you','sample_layout');
              $email->emailFormat('html');

              $email->viewVars(array('user' => 'すずき'));

              $messages = $email->send('コレは本文');

              $this->set('messages',$messages);
    }
}

CakeEmailの初期設定

毎回書くのではなく、初期設定しておくことも可能。
app/Config/email.php.defaultを.phpに変換して使う。

<?php
class EmailConfig{

  public $default = array(
    'transport' => 'Mail',
    'charset' => 'ISO-2022-JP',
    'from' => 'suzuki@example.jp',
    'subject' => 'これはテストメールです。',
  );
}