Debugging CakeEmail, msg sent but not received - cakephp

I'm using CakePHP 2.1.1 and trying to send a simple email with form data. This is the code I have in my controller:
App::uses('CakeEmail', 'Network/Email');
try {
$Email = new CakeEmail();
$Email->from(array('support#pcn.com' => 'PC'));
$Email->to('me#gmail.com');
$Email->subject('New Registration');
if ( $Email->send(serialize($formData)) )
$this->set('email', 'Success');
else
$this->set('email', 'Failure without Exception');
}
catch ( Exception $e ) {
$this->set('email', 'Failure with Exception );
}
When I print out the value of 'email' in my view, it is always 'Success', but I never receive the email (ive checked the spam folder). There are no email related issues in the error log. How do I debug this problem and get the email to send properly?

Related

Cant output the status 422 message in console

here is the screenshot of the output I am using mongodb. created a signup page and now checking whether a user already exists
const existingUser = await db.collection('users').findOne({ email: email });
if (existingUser) {
res.status(422).json({ message: 'User already exists !' });
client.close();
return;
}
Error message : auth-form.js:7 POST http://localhost:3000/api/auth/signup 422 (Unprocessable Entity)
I should expect this error but i also want to show the text 'User already exists !' in the console

I can not send mail in drupal-7

I began to learn about drupal, I perform the function send mail but failed. Please could help me:
$params = array(
'subject' => 'hello',
'body' => 'test',);
$from='nguyen.xuan.luan#vinicorp.com.vn';
$to = 'nguyen.xuan.luan#vinicorp.com.vn';
$mail = drupal_mail('exampe', 'notice', $to, language_default(), $params, $from, TRUE);
error message: Unable to send e-mail. Contact the site administrator if the problem persists.
I think that must have information of mail password but I do not know how. Please can help me?
You need to create one hook i.e. hook_mail in your .module file and set message subject and body there. Below is the working hook_mail() implementation for your code -
function exampe_mail($key, &$message, $params) {
switch($key) {
//switching on $key lets you create variations of the email based on the $key parameter
case 'notice':
$message['subject'] = t('Subject');
//the email body is here, inside the $message array
$message['body'][] = 'This is the body of the email';
break;
}
}

how to send an email to a user in cakephp 2.x

I will greatly appreciate with all my heart if an expert would help me on how to send an email to a user.
am building a registration system. after a user successfully applies for registration, the admin must approve and at the click of the approve button, an email is send to the user and user details are saved in the approved table.
Here is the approve action in the applicationsController.
public function approve($student_id = null) {
if ($this->request->is('post'))
$application = $this->Application->findById($student_id);
$approved['Approved'] = $application['Application'];
$approved['Approved']['student_id'] = $approved['Approved']['student_id'];
$status = array('Application.status' => 'approved');
unset($application['Application']['id']);
unset($application['Application']['receipts']);
$this->loadModel('Approved');
$this->Approved->create();
if ($this->Approved->save($approved)) {
if ($this->Approved->saveField('status', 'approved')){
$this->Session->setFlash(__('The student has been approved'));
$email=$this->request->data['Application']['email'];
$this->Email->to = $email;
$this->Email->subject = 'Registration request approval';
$this->Email->from = 'ernestmwesha#gmail.com';
$this->Email->template = 'template';
$this->Email->smtpOptions = array(
'port' => '465',
'timeout' => '30',
'host' => 'ssl://smtp.gmail.com',
'username' => 'ernestmwesha#gmail.com',
'password' => 'mweshaernest',
);
$this->Email->delivery = 'smtp';
if($this->Email->send()){
return true;
}
else{
echo $this->Email->smtpError;
}
$this->Application->delete($student_id);
$this->redirect(array('action' => 'index')); }
} else {
$this->Session->setFlash(__('The student could not be approved.'));
}
$this->set('title_for_layout', 'Approved Requests');
}
after clicking the approved button i get the following error:
Notice (8): Undefined index: Application [APP\Controller\ApplicationsController.php, line 120]
You need to specify at least one destination for to, cc or bcc.
Error: An Internal Error Has Occurred.
.....bot the student gets approved and placed in the approved table
Review u2460470's answer to point you in the right direction for generating emails with CakePHP.
Make sure you have a mail server setup to handle the processing of emails. You might already have one setup locally, something like SquirrelMail, or you may prefer to use a managed, hosted provider (like Gmail). You can find examples of configuring CakePHP to send mail through Gmail in the CakeEmail documentation.
I've had great experiences using Postmark to handle transactional emails. There is a nice plugin, maurymmarques/postmark-plugin, you can use to easily setup Postmark for your CakePHP app.
// in your controller
App::uses('CakeEmail', 'Network/Email');
function somrthing () {
$Email = new CakeEmail();
$Email->from(array('me#example.com' => 'My Site'));
$Email->to('you#example.com');
$Email->subject('About');
$Email->send('My message');
}
Have a look CakeEmail in CakePHP 2.x

Cakephp jquery debug info inside the ajax response

I have a cakephp code that works with the database to search a given card id number and return the balance. the jquery code looks like this.
function subm(event){
$.ajax({
type: "POST",
//contentType: "application/json; charset=utf-8",
dataType:'json',
url:"\/balances\/balance",
data:$("#button_check_balance").closest("form").serialize(),
cache: false,
beforeSend:function(){
$("#loadingDiv").show(1000);
},
success:function (data, textStatus,xhr) {
$("#loadingDivision").hide(1000);
alert("balance is "+data.balance);
return false;
},
//failure: function(msg){alert(msg);},
error: function(xhr, ajaxOptions, thrownError){
$("#loadingDivision").hide(1000);
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
console.log(xhr.responseText);
},
/*complete: function(){
alert("complete");
},*/
});
I have the balancesController and balance.ctp files in place and controller logic looks like this.
function balance() {
$message = "";
$error = "";
$this->layout = 'ajax'; //layout should be ajax based on
Configure::write('debug', 0);
//gets the submitted card number
$card_id = $this->data['balances']['cardId']; //entered card id of the emp
if (!empty($this->data)) {
$this->header('Content-Type: application/json');
try {
$card = $this->Card->getBalance($card_id);
} catch (Exception $e) {
$error = "balance not available";
$resp = json_encode(array('error' => $error));
echo $resp;
exit;
}
if ($this->RequestHandler->isAjax()) {
$this->autoRender = $this->layout = false;
$resp = json_encode(array('cardData' => $cardObj);
echo $resp;
exit;
}
}
}
th problem that I have is - when a balance not available error is occurred "I AM GETTING THE CAKE DEBUG INFOMATION IN MY AJAX RESPONSE."
eg - when I try to access xhr object inside error function on $.ajax event
using "xhr.responseText" I am getting the long output consisting of
<pre class="cake-debug">.......... and at the end of this ONLY I get the error that I have encoded into json.
{"error":"error...."}
I have used Configure::write('debug', 1); and Configure::write('debug', 0); without any luck.as u can see I used Configure::write('debug', 0); in the top of my controller function as well..
please advice me resolve this issue. all your input is very highly appreciated.
If you're getting the debug message that means you have an error in your code and you should fix it instead of hiding it. Read the error message (or paste it here) to find out and fix the problem
You're using a throw/catch. Cake usually does not use exceptions to handle errors, unless you've specifically coded your model to throw exceptions, your error state won't be captured. Possibly $card is just returning false.
Please paste your error here, or on pastebin if it's really long.

Display custom validation messages using CakePHP $validate array

I'm trying to display custom messages like, 'this field should not be empty' or 'name not null' using the $validate array in the model. I have two controllers, main and users.
The index file of the main controller has the login and registration views. The action part of the login and register functions are in the user_controller. If the login and register function validate, they are redirected to the home page of the main controller,else they remain in the index page itself.
I want the validation messages to be displayed in the index page itself. But those messages appear only if there is a separate view file for login and register,i.e, /views/forms/register.ctp and /views/forms/login.ctp exist.
Is there a way to display those validation messages without having a separate view file for those functions? I have given my code below.Someone guide me please.
Model Class:
<?php
class User extends AppModel {
var $name = 'User';
var $components=array('Auth');
var $validate = array(
'name' => array(
'rule' => 'notEmpty',
'message' =>'Name cannot be null.'
),
'password' => array(
'rule' => 'notEmpty'
),
'email_id' => array(
'rule' => 'notEmpty'
)
);
function registerUser($data)
{
if (!empty($data))
{
$this->data['User']['name']=$data['User']['name'];
$this->data['User']['email_id']=$data['User']['email_id'];
$this->data['User']['password']=$data['User']['password'];
$existingUsers= $this->find('all');
foreach($existingUsers as $existingUser):
if($this->data['User']['email_id']==$existingUser['User']['email_id']){
return 0;
}
else{
$this->save($this->data);
$this->data['User']['id']= $this->find('all',array('fields' => array('User.id'),
'order' => 'User.id DESC'
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
endforeach;
}
}
function loginUser($data)
{
$this->data['User']['email_id']=$data['User']['email_id'];
$this->data['User']['password']=$data['User']['password'];
$login=$this->find('all');
foreach($login as $form):
if($this->data['User']['email_id']==$form['User']['email_id'] && $this->data['User']['password']==$form['User']['password'])
{
$this->data['User']['id']= $this->find('all',array('fields' => array('User.id'),
'conditions'=>array('User.email_id'=> $this->data['User']['email_id'],'User.password'=>$this->data['User']['password'])
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
endforeach;
}
}
?>
Controller Class:
<?php
class UsersController extends AppController
{
var $name = 'Users';
var $uses=array('Form','User','Attribute','Result');
var $helpers=array('Html','Ajax','Javascript','Form');
function register()
{
$this->Session->write('userId',$this->User->registerUser($this->data));
$this->User->data=$this->data;
if (!$this->User->validates())
{
$this->Session->setFlash('Please enter valid inputs');
$this->redirect('/main' );
return;
}
if($this->Session->read('userId')==0){
$this->Session->setFlash('You are already a registerd member.Log in your account');
$this->redirect('/main');
}
else{
$this->Session->setFlash('User account created');
$this->redirect('/main/home');
}
}
function login()
{
//$userId=$this->User->loginUser($this->data);
$this->Session->write('userId',$this->User->loginUser($this->data));
$this->User->data=$this->data;
if (!$this->User->validates())
{
$this->Session->setFlash('Please enter valid inputs');
$this->redirect('/main' );
return;
}
if($this->Session->read('userId')>0){
$this->Session->setFlash('Login Successful');
$this->redirect('/main/home');
break;
}
else{
$this->Session->setFlash('Username and password do not match.');
$this->redirect('/main');
}
}
}
?>
View Template:
<!-- File: /views/main/index.ctp-->
<div id="register">
<h3>Register</h3>
<?php
echo $form->create('User',array('action'=>'register'));
echo $form->input('name');
echo $form->input('email_id');
echo $form->input('password');
echo $form->end('Register');
?>
</div>
<div id="login">
<h3>Login</h3>
<?php
echo $form->create('User',array('action'=>'login'));
echo $form->input('email_id');
echo $form->input('password');
echo $form->end('Login');
?>
</div>
I think you're going about it the wrong way. You're doing way too much in the model, and you're also doing almost the same thing in the controller again after the fact. That's not good. Overall, honestly, the code is quite a mess for something so simple.
A huge WTF flag pops up here:
$existingUsers= $this->find('all');
foreach($existingUsers as $existingUser):
if($this->data['User']['email_id']==$existingUser['User']['email_id']){
You're seriously retrieving all users from the database (potentially a hugely expensive task) and then go through them one by one to compare a single field?!
You can simply define a validation rule that says 'email_id' should be unique, and Cake will automatically ask the database if the 'email_id' already exists. http://book.cakephp.org/view/472/isUnique
About your specific problem: You have the same form field twice on the same page, password and email_id fields for the same User model. There's no way for Cake to know which instance of the two fields is supposed to get the error message, they both have the same name. Also, I don't think you want to use validation error messages for the login form, you just want to see if the login was successful or not. Use Session::flash() instead to display an error message for a failed login, it's not field specific.
Take the login and register methods out of your model, they don't belong there. Only specify proper validation rules for the email, name and password fields in the model, they will automatically be checked upon calling $this->User->save() in the controller.
Don't hand-validate anything, unless there's really no way to do it with Cake validation rules (not the case here). If the built-in validation rules don't satisfy what you need to do, you can even make custom rules. http://book.cakephp.org/view/150/Custom-Validation-Rules
PS: Components are not for models. I think you need to learn more about the basics of Cake before continuing: http://book.cakephp.org/view/218/Tutorials-Examples
But, if you want to see your error messages that comes from the validate array you should access the $this->modelName->invalidFields() which will return you the fields that didn't pass the validation and the message that you have setted for them...

Resources