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:
https://github.com/PHPMailer/PHPMailer
After downloading the library, copy to “vendor” folder under /app/vendor.
Further steps:
* Create a controller named as “GmailsController.php” under /app/controller:
<?php App::uses('AppController', 'Controller'); App::import('vendor', 'PHPMailer', array('file' => 'PHPMailer' . DS . 'PHPMailerAutoload.php')); // import PHPMailer library class GmailsController extends AppController { public function index() { if(!empty($_POST['host'])) { $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"; $to_id="naresh.garg@webners.com"; $mail = new PHPMailer; $mail->isSMTP(); $mail->Host =$host; $mail->Port =$port; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Username = $email; $mail->Password = $password; $mail->addAddress($to_id); $mail->Subject = $subject; $mail->msgHTML($message); 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:
<?php class Gmail extends AppModel { } ?>
* Create a file named as “index.ctp” under /app/View/Gmails:
<?php 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’));
Output: