Cakephp | How to send email using google api (gmail) in cakephp 2.x ?

| By Webner

How to send email using google api (gmail) in cakephp 2.x?

Answer: When you send email using google api, you’ll need:

1. Cakephp 2.x
2. A Google account with Gmail enabled.
3. PHPMailer Library.

Download PHPMailer library from below link:

After downloading the library, copy to “vendor” folder under /app/vendor.

Further steps:
* Create a controller named as “GmailsController.php” under /app/controller:

App::uses('AppController', 'Controller');
App::import('vendor', 'PHPMailer', array('file' => 'PHPMailer' . DS . 'PHPMailerAutoload.php')); // import PHPMailer library
class GmailsController extends AppController {
public function index() {
$email = $_POST[‘ username’]; //user email_id
$password = $_POST['password']; //root user password
$host = $_POST['host'];
$port = $_POST['port'];
$message ="A beautiful saying:-The past is to prove that no one is perfect and the future is to prove that everyone can change..!";
$subject ="Message";
$mail = new PHPMailer;
$mail->Host =$host;
$mail->Port =$port;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = $email;
$mail->Password = $password;
$mail->Subject = $subject;
if (!$mail->send()) {
$error = "Mailer Error: " . $mail->ErrorInfo;
echo '<p id="para">'.$error.'</p>';
else {
echo '<p id="para">Message sent!</p>';
} } }

* Create a Model named as “Gmail.php” under /app/Model:

class Gmail extends AppModel

* Create a file named as “index.ctp” under /app/View/Gmails:

echo $this->FORM->create('Emails');
echo $this->FORM->input('smtpurl', array(
'label' => 'SMTP_Url',
'name' => 'host'
echo $this->FORM->input('port', array(
'label' => 'Port no',
'name' => 'port'
echo $this->FORM->input('username', array(
'label' => 'Username',
'name' => 'username'
echo $this->FORM->input('password', array(
'type' => 'password',
'name' => 'password'
echo $this->FORM->submit('submit');
echo $this->FORM->end();

So, in the last step to call the gmail controller under /app/config/routes.php
Router::connect(‘/’, array(‘controller’ => ‘gmails’, ‘action’ => ‘index’));



Leave a Reply

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