CakePHPで標準のメールコンポーネントでGmailのSMTPサーバーを使う。

まさか僕がCakePHPの話題を書くとは思いませんでしたが、何となくネタがないので書きます。

OCN へのメールは、SMTP を経由しないと迷惑メールに行く件について。

昨夜、某英会話サービスの運営で、メールが届かないというご連絡を頂きました。そこで調べてみると、OCN|OCN迷惑メール対策の、ISPのメールサーバーを経由せず、動的IPアドレスから直接送信されるOCN宛のメールを規制しますとあり、これに該当してしまったようです。
ってか、固定IPなんやけどなぁ。と思いつつ、面倒なので GmailSMTP サーバーを利用することにしました。
CakePHP の標準のメールコンポーネントSMTPを利用することができます。
Sending A Message Using SMTP :: Email :: Core Components :: The Manual :: 1.3 Collection :: The Cookbookによると、

    /* SMTP Options */
    $this->Email->smtpOptions = array(
        'port'=>'465', 
        'timeout'=>'30',
        'host' => 'ssl://smtp.gmail.com',
        'username'=>'your_username@gmail.com',
        'password'=>'your_gmail_password',
    );
    /* Set delivery method */
    $this->Email->delivery = 'smtp';

    /* Do not pass any args to send() */
    $this->Email->send();

    /* Check for SMTP errors. */
    $this->set('smtp-errors', $this->Email->smtpError);

これで良いそうです。
で、例えば以下のようにするしたとすると、どうも送れません。

    /* SMTP Options */
    $this->Email->smtpOptions = array(
      'port'=>'465',
      'timeout'=>'30',
      'host' => 'ssl://smtp.gmail.com',
      'username'=>'noreply@langrich.com',
      'password'=>'password');

    /* Set delivery method */
    $this->Email->delivery = 'smtp';

    /* mail options */
    $this->Email->to = 'test@langrich.com';
    $this->Email->subject = '件名';
    $this->Email->replyTo = 'noreply@langrich.com';
    $this->Email->from = 'Langrich <noreply@langrich.com>';
    $this->Email->template = 'template_name';
    $this->Email->sendAs = 'text';
    $this->Email->send();

555 5.5.2 Syntax error というエラー。

GmailSMTP サーバーからは上記のエラーで弾かれてしまったようで、これはなんぞやと調べてみたら、どうやらメールのヘッダで、アドレスは "<" ">" で括らないとだめよ。という事が原因でした。
結果として、

    /* SMTP Options */
    $this->Email->smtpOptions = array(
      'port'=>'465',
      'timeout'=>'30',
      'host' => 'ssl://smtp.gmail.com',
      'username'=>'noreply@langrich.com',
      'password'=>'password');

    /* Set delivery method */
    $this->Email->delivery = 'smtp';

    /* mail options */
    $this->Email->to = '<test@langrich.com>'; // ここと
    $this->Email->subject = '件名';
    $this->Email->replyTo = '<noreply@langrich.com>'; // ここ
    $this->Email->from = 'Langrich <noreply@langrich.com>';
    $this->Email->template = 'template_name';
    $this->Email->sendAs = 'text';
    $this->Email->send();

という形でメールアドレスを<>で括ってあげると、エラー出ずに送信できました。最後に行きつくところは、RFC というお話でした。めでたしめでたし。