How to send email in cakephp

Today we are going to talk about email library of cakephp, Cakephp is one of great php framework.
It comes with some great useful libraries, So in this tutorial we are only talking about email sending library.

First you need to create email template. under app/views/layouts/ you can see the structure below.

email/
   html/
      default.ctp
   text/
     default.ctp

If you are going to send a normal text email create your text template under text folder If html email then create html template under html folder. This example will show both methods.

In this example we created templates for a registration email with the following structure:
Text Email:-

app/views/elements/email/text/registrationSuccess.ctp

Dear  echo $name; ?>
Thank you for registering with us. Please go to here to complete your registration process.

Html Email:-

app/views/elements/email/html/registrationSuccess.ctp

Dear  echo $name; ?>
Thank you for registering with us. Please go to here to complete your registration process.

After that add below line In your controller to enable the email component.

var $components = array('Email');

Create email sending action in your controller

UsersController.php

public function sendEmail() {
    $this->Email->smtpOptions = array(
      'port'=>'587',
      'timeout'=>'30',
      'host' => 'smtp.gmail.com',
      'username'=>'YOUR_GMAIL_EMAILID',
      'password'=>'GMAIL_EMAILID_PASSWORD'
    );
    $formName = 'Rohit Kumar';
    $toName =   'XYZ Name'
    $this->Email->delivery = 'smtp';
    $this->Email->from = $formName; // Your Name
    $this->Email->to = $toName; //Recipient Name 
    $this->set('name', $toName);
    $this->Email->subject = 'Complete Your Registration';
    $this->Email->template = 'registrationSuccess';
    $this->Email->sendAs = 'both';
    $this->Email->send();
}

Home this tutorial will help you to understand email library of cakephp you can learn more email sending features from cakephp official document.
http://book.cakephp.org/2.0/en/core-utility-libraries/email.html

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.

Leave a Reply

Your email address will not be published. Required fields are marked *

Top