Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active August 14, 2018 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yano3nora/c05fc2a9b02981b2af5fcfe0bdf0f67e to your computer and use it in GitHub Desktop.
Save yano3nora/c05fc2a9b02981b2af5fcfe0bdf0f67e to your computer and use it in GitHub Desktop.
[cakephp: Email] Email class on CakePHP3. #php #cakephp

Email

Email クラス - cookbook
添付ファイルを送る - cookbook

Email 送信

// In Controller with `use Cake\Mailer\Email;`
try {
  $email = new Email('default');
  $email
    ->template('my_template', 'default')
    ->emailFormat('text')
    ->subject('【'.APP_NAME.'】 '.MAIL_SUBJECTS[$subject])
    ->setTo('mail.to@example.com')
    ->setFrom($User->email)
    ->setBcc($bccAddresses)  // Passable Array or String
    ->setReplyTo($replyToAddresses)
    ->viewVars([
      'name'   => $User->name,
      'body'   => $body,
      'footer' => $User->mail_footer,
    ])
    ->send();
  $this->Flash->success('Sent your mail.');
} catch (Exception $e) {
  $this->Flash->error($e->getMessage());
}
$this->redirect($this->referer());

SMTP 転送

<?php

/**
 * Mail Transport 
 * @see https://qiita.com/frost_star/items/4a56cec1f5de5eccbd09
 */

// In app.php
'EmailTransport' => [
  'default' => [
    'className' => 'Smtp',
    // The following keys are used in SMTP transports
    'host' => 'ssl://smtp.gmail.com',
    'port' => 465,
    'timeout' => 30,
    'username' => 'gmailのメールアドレス',
    'password' => 'gmailのパスワード',
    'transport' => 'Smtp',
    'client' => null,
    'tls' => null,
    'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
  ],
],


// In Controller
use Cake\Mailer\Email;

class UsersController extends AppController {
    public function send(){
        $email = new Email('default');
        $email->from(['送り元アドレス' => '名前'])
              ->to('送り先アドレス')
              ->subject('タイトル')
              ->send('本文');
    }
}

localhost へ SMTP 送信

// In app.php
'EmailTransport' => [
  'default' => [
    'className' => 'Smtp',
    // The following keys are used in SMTP transports
    'host' => 'localhost',
    'port' => 25,  // TLS 対応した Postfix とかで受ける想定
    'timeout' => 30,
    'transport' => 'Smtp',
    'client' => null,
    'tls' => null,
    'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
  ],
],
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment