How to send Email confirmation link via smtp Cakephp - email

I am working in cakephp and want to send confirmation link on user signup but i do not know much about SMTP.
Here is What i have written I am using Token to confirm email which will expire next time if user hit the same confirmation link.
Here is usercontroller/signup method:
public function signup()
{
$this->layout = 'main';
if ($this->request->is('post')) {
$this->User->create();
$this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
$hash = sha1($this->request->data['User']['username'] . rand(0, 100));
$this->request->data['User']['tokenhash'] = $hash;
if ($this->User->validates()) {
$this->User->save($this->request->data);
$ms = 'Click on the link below to complete registration ';
$ms .= 'http://localhost/FindTutor/users/verify/t:' . $hash . '/n:' . $this->data['User']['username'] . '';
$ms = wordwrap($ms, 70);
$this->Email->from = 'usman.jamil0308#gmail.com';
$this->Email->to = $this->request->data['User']['email'];
$this->Email->subject = 'Confirm Registration..';
$this->Email->send($ms);
$this->Session->setFlash('Please Check your email for validation Link');
$this->redirect('/users/login');
}
}
}
Here is users/verify method to confirm if user hit the confirmation link.
public function verify(){
//check if the token is valid
if (!empty($this->passedArgs['n']) && !empty($this->passedArgs['t'])){
$name = $this->passedArgs['n'];
$tokenhash = $this->passedArgs['t'];
$results = $this->User->findByUsername($name);
if ($results['User']['activate']==0){
//check the token
if($results['User']['tokenhash']==$tokenhash)
{
$results['User']['activate']=1;
//Save the data
$this->User->save($results);
$this->Session->setFlash('Your registration is complete');
$this->redirect('/users/login');
exit;
}
else{
$this->Session->setFlash('Your registration failed please try again');
$this->redirect('/users/register');
}
}
else {
$this->Session->setFlash('Token has alredy been used');
$this->redirect('/users/register');
}
}else
{
$this->Session->setFlash('Token corrupted. Please re-register');
$this->redirect('/users/register');
}
}
Error is somthing like this:
mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

try to use mailjet and configure your sever (wamp or xampp)the directorie sendmail and configure your app.php like that
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => '',
'password' => '',
'client' => null,
'tls' => null,
],
'mailjet' => [
'className' => 'smtp',
// The following keys are used in SMTP transports
'host' => 'in-v3.mailjet.com',
'username' => 'copy that from your account mailjet',
'password' => 'copy that from your account mailjet',
'port' => 587,
'timeout' => 3000,
'client' => null,
'tls' => null,
],
],
'Email' => [
'default' => [
'transport' => 'mailjet',
'from' => 'xxxxxx#gmail.com',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
],
],

public $smtp = array(
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'username' => 'your email id',
'password' => 'your password',
'transport' => 'Smtp',
);
App::uses('CakeEmail', 'Network/Email');
$Email = new CakeEmail('smtp');
$Email->from('info#email.com');
$Email->to($email);
$message = "hello";
$Email->send($message);

First Include Email Component in your App Controller like this :
public $components = array(
'Email'
);
Create a sendMail function in your App controller like this
public function _sendMail( $to, $from, $replyTo, $subject, $element,$parsingParams = array(),$attachments ="", $sendAs = 'html', $bcc = array()){
$port = '';
$timeout = '';
$host = '';
$username = '';
$password = '';
$client = '';
$toAraay = array();
if (!is_array($to)) {
$toAraay[] = $to;
} else {
$toAraay = $to;
}
$this->Email->smtpOptions = array(
'port' => "$port",
'timeout' => "$timeout",
'host' => "$host",
'username' => "$username",
'password' => "$password",
'client' => "$client"
);
$this->Email->delivery = 'smtp';
foreach ($parsingParams as $key => $value) {
$this->set($key, $value);
}
foreach ($toAraay as $email) {
$this->Email->to = $email;
$this->Email->subject = $subject;
$this->Email->replyTo = $replyTo;
$this->Email->from = $from;
if(!empty($bcc)){
$this->Email->cc = $bcc[0];
}
if ($attachments!="") {
$this->Email->attachments = array();
$this->Email->attachments[0] = $attachments ;
}
$this->Email->template = $element;
$this->Email->sendAs = $sendAs;
$this->Email->send();
$this->Email->reset();
}
}
Create a sendmail.ctp file in View/Emails/html
Add this content in file and also add your header or footer
<?php echo $message; ?>
Now whenever you want to send email call this function like this :
$this->_sendMail($to, $from, $replyTo, $subject, 'sendmail', array('message' => $message), "", 'html', $bcc = array());
Now you can implement your logic for verification email like this :
$message = 'Click on the link below to complete registration ';
$message .= 'http://localhost/FindTutor/users/verify/t:' . $hash . '/n:' . $this->data['User']['username'] . '';
$from = 'usman.jamil0308#gmail.com';
$to = $this->request->data['User']['email'];
$subject = 'Confirm Registration..';
$replyTo = 'usman.jamil0308#gmail.com';
$this->_sendMail($to, $from, $replyTo, $subject, 'sendmail', array('message' => $message), "", 'html', $bcc = array());

Related

Sending Email with Cakephp 3

I've been using this library for sending mail
https://github.com/PHPMailer/PHPMailer
But I'm not getting the Email Send
Invalid address: (From): XXX
Array ( [error] => 1 [message] => Mailer Error: Invalid address: (From): XXX )
What I did : Disable 2 Step verification into Gmail
And Enabled Allow Less Secure Apps On
PagesController.php
<?php
namespace App\Controller;
class PagesController extends AppController
{
public $components = array("Email");
public function index()
{
$to = 'myemail#gmail.com';
$subject = 'Hi buddy, i got a message for you.';
$message = 'Nothing much. Just test out my Email Component using PHPMailer.';
try {
$mail = $this->Email->send_mail($to, $subject, $message);
print_r($mail);
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
exit;
}
}
EmailComponent.php
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Core\App;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require ROOT. '/vendor/phpmailer/phpmailer/src/Exception.php';
require ROOT. '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require ROOT. '/vendor/phpmailer/phpmailer/src/SMTP.php';
class EmailComponent extends Component {
public function send_mail($to, $subject, $message)
{
// date_default_timezone_set('Asia/Calcutta');
$sender = "XXX"; // this will be overwritten by GMail
$header = "X-Mailer: PHP/".phpversion() . "Return-Path: $sender";
$mail = new PHPMailer();
$mail->SMTPDebug = 2; // turn it off in production
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "XXX";
$mail->Password = "XXX";
$mail->SMTPSecure = "tls"; // ssl and tls
$mail->Port = 587; // 465 and 587
$mail->SMTPOptions = array (
'tls' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
),
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->From = $sender;
$mail->FromName = "From Me";
$mail->AddAddress($to);
$mail->IsHTML(true);
$mail->CreateHeader($header);
$mail->Subject = $subject;
$mail->Body = nl2br($message);
$mail->AltBody = nl2br($message);
// return an array with two keys: error & message
if(!$mail->Send()) {
return array('error' => true, 'message' => 'Mailer Error: ' . $mail->ErrorInfo);
} else {
return array('error' => false, 'message' => "Message sent!");
}
}
}
Fixed I had to replace
thoses three lines in EmailComponent
$sender = "xxx#gmail.com";
$mail->Username = "xxx#gmail.com";
$mail->Password = "GMAIL_PASSWORD";

Cakephp email functionality giving Unknown email configuration "gmail"

I have written generating email functionality inside public function add().
My idea is to send my to the users who had registered.
my add functionality looks like this.
add functionality is working fine but mail generation giving error says Unknown email configuration "gmail". Any help please.
app/Controller/UsersController.php
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$data[] = $this->request->data;
foreach($data as $row){
$email_name = $row['User']['username'];
$password = $row['User']['password'];
}
$data = array();
$subject = "Visualization Tool Login credentials";
// From
$header="manasasirsi17#gmail.com";
// Your message
$message="welcome user\r\n";
$message.="Thank You for Registering\r\n";
$message.="your login details are as given below\r\n";
$message.="username:$email_name\r\n";
$message.="password:$password\r\n";
App::uses('CakeEmail', 'Network/Email');
$smtp = new CakeEmail('smtp');
$smtp->from(array($header => $header));
$smtp->to($email_name);
$smtp->subject($subject);
$smtp->emailFormat('html');
$Email->send($message);
$this->Session->setFlash(__('Login Details are sent to You via Email.'));
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
}
app/Config/email.php
class EmailConfig {
public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
public $smtp = array(
'transport' => 'Smtp',
'host' => 'ssl://smtp.gmail.com',
'port' => 25,
'timeout' => 30,
'username' => 'manasasirsi17#gmail.com',
'password' => 'secure',
'client' => null,
'log' => false
);
public $fast = array(
'from' => 'you#localhost',
'sender' => null,
'to' => null,
'cc' => null,
'bcc' => null,
'replyTo' => null,
'readReceipt' => null,
'returnPath' => null,
'messageId' => true,
'subject' => null,
'message' => null,
'headers' => null,
'viewRender' => null,
'template' => false,
'layout' => false,
'viewVars' => null,
'attachments' => null,
'emailFormat' => null,
'transport' => 'Smtp',
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => true,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
}
You've not defined a gmail email config in your EmailConfig class. This line:-
$Email = new CakeEmail('gmail');
should be from the looks of your code:-
$Email = new CakeEmail('smtp');
The parameter you pass to CakeEmail determines which of the defined configs in EmailConfig you want to use. If you had wanted to pass it gmail you would have needed to add a $gmail property to the EmailConfig class containing the configuration.

how to send a mail using cakephp

I have some code for send to mail but it's not working properly.
My code is here:
class EmailsController extends AppController
{
var $name="Email";
var $uses = NULL;
public function index()
{
App::import('Component', 'Email');
$path=WWW_ROOT."img";
$filename="Desert.jpg";
$email->from = 'pal#gmail.com';
$email->to='abc#gmail.com';
$email->subject='test mail';
$email->template = 'simple_message';
$email->attachments = array($path.$filename);
$email->SendAs='html';
if($email->send())
{
$this->session->setFlash("Email Send Successfully");
}
else
{
$this->session->setFlash("Email is not send");
}
}
}
I am getting the error like:
Call to undefined method stdClass::send()
Why don't you use var $components? Include Email component the right way:
class EmailsController extends AppController
{
var $name="Email";
var $components = array('Email');
var $uses = NULL;
public function index() {
$path=WWW_ROOT."img";
$filename="Desert.jpg";
$this->Email->from = 'pal#gmail.com';
$this->Email->to='abc#gmail.com';
$this->Email->subject='test mail';
$this->Email->template = 'simple_message';
$this->Email->attachments = array($path.$filename);
$this->Email->sendAs='html';
if($this->Email->send()) {
$this->Session->setFlash("Email Send Successfully");
} else {
$this->Session->setFlash("Email is not send");
}
}
}
For more info please visit: http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
<?php
App::uses('CakeEmail', 'Network/Email');
$email = new CakeEmail( $smtp );
$email->to( 'test#example.com' );
$email->subject(__("Reset Password") );
$email->emailFormat('html');
$email->send($body);
?>
For SMTP:
save this below code with "email.php" file in app/Config folder and put your smtp details in $smtp array. and assign $smtp variable in
new CakeEmail($smtp);
<?php
class EmailConfig {
public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
public $smtp = array(
'transport' => 'Smtp',
'from' => array('site#localhost' => 'My Site'),
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => false,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
}
?>

sending email with cakephp2

I'm having problems sending a mail with cakephp2, I know I can send emails because I have my postfix configured, and I can send e-mails with command line or php. So please, can you send me an example of cakephp2 sending emails.
This is the error message
Invalid email: "you#localhost"
Error: An Internal Error Has Occurred.
I've also tried with the ssl via gmail and it doesn't work either, and it's giving me a really hard time.
thanks guys
by the way, I'm trying the exact example of this url http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
Your app/config/Email.
class EmailConfig {
public $gmail = array(
'port' => '465',
'timeout' => '300',
'host' => 'ssl://smtp.gmail.com',
'username' => '<your_email>#gmail.com',
'password' => '<you_password>',
'transport' => 'Smtp'
); }
your file = app/controller/appController.php insert this function
public function sendEmail($type, $options){
try {
$Email = new CakeEmail($type);
$Email->config($options);
$Email->template = "email_confirmation";
$Email->emailFormat('html');
//$this->idCrudRash = $options;
$Email->send();
} catch (SocketException $e) {
die('Erro ao enviar email:'. $e->getMessage());
$this->log(sprintf('Erro ao enviar email: %s', $e->getMessage()));
}
}
for user: app/controller/contato.php
$options = array(
'emailFormat' => 'html',
'from' => array(
$config['email_noanswer'] => $config['site_name']
),
'subject' => 'Confirmação de Cadastro',
'to' => $this->request->data['User']['email'],
//'template' => 'default',
'template' => 'email_confirmation',
'viewVars' => array(
'title_for_layout' => 'Confirmação de Email ' . $config['site_name'],
'name' => $this->request->data['User']['name'],
'email' => $this->request->data['User']['email'],
//'cpf' => base64_encode($this->request->data['User']['cpf']),
'site_name' => $config['site_name'],
),
);
$this->sendEmail('gmail', $options);
In your email.php file, please remove the default 'from' value, it overrides your passed param.
public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost', // remove this line
...
);
In app/config/Email
public $smtp = array(
'transport' => 'Smtp',
'from' => array('no-reply#xyz.com' => 'no-reply#xyz.com'),
'host' => 'ssl://smtp.abc.com',
'port' => 465,
'timeout' => 30,
'username' => 'username',
'password' => 'password',
'client' => null,
'log' => false,
);
In Your Controller
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
public function index()
{
$this->layout = 'layout';
$this->set('title', "Title");
if ($this->request->is('Post')) {
if (!empty($this->request->data)) {
if ($this->Modal->Save($this->request->data)) {
$to = 'test#anc.com';
$subject = 'Your_subject';
$message = $this->request->data;
if ($this->sendmail($to, $subject, $message)) {
echo"sent";die;
}
} else {
echo"wrong";die;
}
}
}
}
public function sendmail($to = null, $subject = '', $messages = null, $ccParam = null, $from = null, $reply = null, $path = null, $file_name = null)
{
$this->layout = false;
$this->render(false);
$name = $messages['Modalname']['name'];
$email = $messages['Modalname']['email'];
$Email = new CakeEmail();
$Email->config('smtp');
$Email->viewVars(array('name' => $name, 'email' => $email));
$Email->template('comman_email_template', 'comman_email_template');
return $Email->emailFormat('html')
->from(array('no-reply#xyz.com' => 'no-reply#xyz.com'))
->to($to)
->subject($subject)
->send();
}
Create a layout and view for email template.and add the data value that have been sent.

CakePHP 2 sends out 2 emails each time

I've come across a strange error in CakePHP when sending a contact form to a recipient via e-mail. When a contact form is filled out and is submitted, CakePHP then sends the e-mail to recipient absolutely fine. But instead of sending one email once it seems to send two emails at the same time.
My controller code is this:
var $helpers = array('Html', 'Form', 'Js');
var $components = array('Email', 'Session');
public function index() {
$this->layout = 'modal';
if(isset($this->data['Contact'])) {
$userName = $this->data['Contact']['yourname'];
$userPhone = $this->data['Contact']['yourtelephone'];
$userEmail = $this->data['Contact']['youremail'];
$userMessage = $this->data['Contact']['yourquestion'];
$email = new CakeEmail();
$email->viewVars(array(
'userName' => $userName,
'userPhone' => $userPhone,
'userEmail' => $userEmail,
'userMessage' => $userMessage
));
$email->subject(''.$userName.' has asked a question from the website');
$email->template('expert', 'standard')
->emailFormat('html')
->to('recipient-email#gmail.com')
->from('postman#website.co.uk', 'The Postman')
->send();
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}
And this is the code for the contact form:
<?php
echo $this->Form->create('Contact', array('url' => '/contact/ask-the-expert/', 'class' => 'contact'));
echo $this->Form->input('yourname', array(
'type' => 'text',
'label' => 'Your Name <span class="star">*</span>',
));
echo $this->Form->input('yourtelephone', array(
'type' => 'text',
'label' => 'Your Telephone',
));
echo $this->Form->input('youremail', array(
'type' => 'text',
'label' => 'Your Email <span class="star">*</span>',
));
echo $this->Form->input('yourquestionAnd ', array(
'type' => 'textarea',
'label' => 'Your Question <span class="star">*</span>',
));
echo $this->Form->submit();
echo $this->Form->end();
?>
Cheers!
Put your Mail Send code inside if ($this->request->is('post')) {} and try.
UPDATE
updated the code.
var $helpers = array('Html', 'Form', 'Js');
var $components = array('Email', 'Session');
public function index() {
$this->layout = 'modal';
if(isset($this->data['Contact'])) {
$userName = $this->data['Contact']['yourname'];
$userPhone = $this->data['Contact']['yourtelephone'];
$userEmail = $this->data['Contact']['youremail'];
$userMessage = $this->data['Contact']['yourquestion'];
$email = new CakeEmail();
$email->viewVars(array(
'userName' => $userName,
'userPhone' => $userPhone,
'userEmail' => $userEmail,
'userMessage' => $userMessage
));
$email->subject(''.$userName.' has asked a question from the website');
$email->template('expert', 'standard')
->emailFormat('html')
->to('recipient-email#gmail.com')
->from('postman#website.co.uk', 'The Postman')
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}