23
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP3のメール送信はMailerクラスにすっきりまとめよう

Posted at

CakePHP3.1からMailerクラスが導入されており、メール送信機能をまとめることが出来るようになっています。

使い方

Mailerクラスの作成

src/Mailer/UserMailer.php を作成します。

<?php
namespace App\Mailer;

use Cake\Mailer\Mailer;

class UserMailer extends Mailer
{
    public function welcome($user)
    {
        // $thisからEmailクラスにアクセス可能
        $this
            ->profile('default')
            ->to($user->mail)
            ->subject('タイトル')
            ->template('welcome_mail')
            ->layout('default');
    }

    public function resetPassword($user)
    {
        // パスワードリセットメール送信等々、User関連のメール送信機能を作成
    }
}


Mailerクラスへアクセス(コントローラーからアクセス)

<?php
namespace App\Controller;

// MailerAwareTrait追加
use Cake\Mailer\MailerAwareTrait;

class UsersController extends AppController
{
    // MailerAwareTrait追加(getMailer()が実装されてる)
    use MailerAwareTrait;

    public function register()
    {
        $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->data())
            if ($this->Users->save($user)) {

                // UserMailerを取得して、welcome でメール送信する
                $this->getMailer('User')->send('welcome', [$user]);

            }
        }
        $this->set('user', $user);
    }
}
23
17
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
23
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?