LoginSignup
15

More than 5 years have passed since last update.

CakePHPでMailを使う

Posted at

CakePHPでMailを使う

環境

  • SMTP:Google Appsを使用
  • CakePHPのバージョン:2.6

CakeEmailの読み込み

CakePHP全体で使用の場合

/app/Config/bootstrap.phpに下記を追加

App::uses( 'CakeEmail', 'Network/Email');

コントローラーで使用する場合

ファイルの先頭で読み込む

App::uses( 'CakeEmail', 'Network/Email');
class EmailTestsController extends AppController{
    public function index(){
        echo 'メール送信テスト!';
    }
}

CakeEmailの設定

/app/config/email.php.default/app/config/email.phpにリネーム
任意の配列を作成してそこに設定を記載していきます。

例:Gmailの場合

class EmailConfig {
    public $default = array(
        ....
    );
    public $gmail = array(
        'host' => 'ssl://smtp.gmail.com',
        'port' => 465,
        'username' => 'username@gmail.com', // ユーザ名
        'password' => 'password',           // パスワード
        'transport' => 'Smtp'
    );
}

送信処理

送信処理メール本文ベタ書き)

$email = new CakeEmail( 'gmail');                        // インスタンス化
$email->from( array( 'sender@domain.com' => 'Sender'));  // 送信元
$email->to( 'reciever@domain.com');                      // 送信先
$email->subject( 'メールタイトル');                      // メールタイトル

$email->send( 'メール本文');                             // メール送信

送信処理(メール本文をテンプレート化)

$email = new CakeEmail( 'gmail');                        // インスタンス化
$email->from( array( 'sender@domain.com' => 'Sender'));  // 送信元
$email->to( 'reciever@domain.com');                      // 送信先
$email->subject( 'メールタイトル');                      // メールタイトル

$email->emailFormat( 'text');                            // フォーマット
$email->template( 'templete');                           // テンプレートファイル
$var1 = "test1";
$var2 = "test2";
$email->viewVars( compact( 'var1', 'var2'));             // テンプレートに渡す変数

$email->send();                                          // メール送信

emailFormat

  • text
  • html
  • both(templateでtext,html両方用意しておくとマルチパートメールを送信できる。)

template

/app/View/Emails/以下に保存

htmlの場合/app/View/Emails/html/*ctp
textの場合/app/View/Emails/html/*ctp

viewVars

必要な変数をcompactでまとめて引き渡せる。
compact( 'var1', 'var2')の場合

メール送信の末尾のデフォルトメッセージを消す

下記を編集する
/app/View/Layouts/Emails/text/default.ctp
/app/View/Layouts/Emails/html/default.ctp

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
15