LoginSignup
31
38

More than 5 years have passed since last update.

【CakePHP】CakeEmailでメールの送信

Last updated at Posted at 2015-04-16

CakePHPでは、CakeEmailというメール送信クラスが用意されている。

送信のための設定を行う

app/Config/email.php

送信時に設定することもできるが、SMTPサーバなど動的に設定する必要がないものはここへまとめる。

class EmailConfig{
  public $default = array(
    /*
    *  Smtp:SMTPサーバを使う場合
    *  Mail:PHPのmail関数を使う場合
    */
    'transport' => 'Smtp',
    'host' => 'localhost',
    'port' => 25,
  );
}

CakeEmailクラス読み込み

忘れやすいので。

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

送信設定と送信処理

//読み込む設定ファイルの変数名を指定
$email = new CakeEmail('default');
$email->from('foo@example.com');
$email->to('bar@example.com');
$email->subject('メールタイトル');

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

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

//読み込む設定ファイルの変数名を指定
$email = new CakeEmail('default ');
$email->from('foo@example.com');
$email->to('bar@example.com');

//HTMLorテキストメール
$email->emailFormat('text');
//テンプレート
$email->template('alert_mail');
//テンプレートへ渡す変数。[変数名=>値]
$email->viewVars([
  'name'=>'鈴木'
]);

$email->subject('メールタイトル');
$email->send();

テンプレートの場所

テキストメール:app/View/Emails/text配下
htmlメールapp/View/Emails/html配下

添付ファイルの設定

添付ファイルと実ファイルが同じ場合

$email->attachments('/path/to/photo.jpg');

添付ファイルと実ファイルが異なる場合

$email->attachments([
  'photo.jpg'=>[
    'file'=>'/path/to/file.jpg',
    'minetype'=>'image/jpeg'
]);

宛先toの設定

送信先のみ

$email->to([
  'suzuki@exmaple.com',
  'sato@exmaple.com'
])

表示名

送信先=>表示名

$email->to([
  'suzuki@exmaple.com'=>'鈴木',
  'sato@exmaple.com'=>'佐藤',
)
31
38
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
31
38