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');
}
}
}
Related
I have a web site which is in English and Arabic. I converted the text into Arabic but the form labels and error message is not converting. I am using gettext adapter and how do i convert this labels. I am using Zend_Form and creating object of this form and passign this to view.
Bootstrap file
protected function _initTranslate() {
$translate = new Zend_Translate('gettext', APPLICATION_PATH . "/lang/", null, array('scan' => Zend_Translate::LOCALE_DIRECTORY));
$registry = Zend_Registry::getInstance();
$registry->set('Zend_Translate', $translate);
//Zend_Form::setDefaultTranslator($translate);
$translate->setLocale('ar');
}
public function _initRoutes() {
$this->bootstrap('FrontController');
$this->_frontController = $this->getResource('FrontController');
$router = $this->_frontController->getRouter();
$langRoute = new Zend_Controller_Router_Route(
':lang', array(
'lang' => 'ar',
'module' => 'default',
'controller' => 'index',
'action' => 'index'
), array(
'lang' => 'en|ar'
)
);
$defaultRoute = new Zend_Controller_Router_Route(
':controller/:action', array(
'module' => 'default',
'controller' => 'index',
'action' => 'index'
)
);
$defaultRoute = $langRoute->chain($defaultRoute);
$router->addRoute('langRoute', $langRoute);
$router->addRoute('defaultRoute', $defaultRoute);
}
protected function _initLanguage() {
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new My_Controller_Plugin_Language());
}
Form
class Application_Form_Contactus extends Zend_Form {
public function init() {
// Set the method for the display form to POST
$this->setMethod('post');
$this->addElement('text', 'name', array('label' => 'Name', 'class' => 'inputbox',
'filters' => array('StringTrim'),
'required' => true));
// Add an email element
$this->addElement('text', 'email', array('label' => 'Email', 'class' => 'inputbox',
'required' => true, 'filters' => array('StringTrim'), 'validators' => array('EmailAddress')));
$this->addElement('submit', 'submit', array(
'required' => false,
'label' => 'Send',
'value' => 'save',
'class' => 'submit-but',
'attribs' => array('type' => 'submit'),
));
}
}
Controller
$form = new Application_Form_Contactus();
$form->setAction($this->view->getSiteUrl() . 'Contactus');
$translate = Zend_Registry::get('Zend_Translate');
$form->element->setTranslator($translate);
$this->view->form = $form;
view
echo $this->form;
Try to attach to the Zend_Form object as a global translator. This will also translate validation error messages :
Zend_Form::setDefaultTranslator($translate);
Or you can do this :
Zend_Validate_Abstract::setDefaultTranslator($translator);
Please see zend form i18n
Try to set default translator.
Zend_Form::setDefaultTranslator($translate);
One more alternate way could be:
$form = new Application_Form_Contactus();
$translate = Zend_Registry::get('Zend_Translate');
foreach ($form->getElements() as $key => $element) {
$element->setTranslator($translate);
}
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',
);
}
?>
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.
I got RegisterController.php and inside of it I got:
class RegisterController extends AppController {
public $name = 'Register';
public $components = array('Session');
public function index() {
if ($this->request->is('account')) {
// if ($this->Post->save($this->request->data)) {
echo "got it";
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
// }
}
}
}
My /View/Register/index.tcp file:
<?php
echo $this->Form->create('Account');
echo $this->Form->input('username');
echo $this->Form->input('password');
$options = array(
'label' => 'Register',
'class' => 'submit'
);
echo $this->Form->end($options);
?>
And my /Model/Account.php file:
<?php
class Account extends AppModel {
public $name = 'Account';
public $validate = array(
'username' => array(
'rule' => 'notEmpty'
),
'password' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Can not be empty.'
),
'minLength' => array(
'rule' => array('minLength', '8'),
'message' => 'Min. 8 chars.'
)
)
);
}
?>
The problem is that, I'm clicking on the submit button, and nothing happends. It should at least check for validation.
Where is the error?
Should work if you add the action in options:
echo $this->Form->create('Account', array('action' => 'your/url'));
I'm trying to figure out how to get this zend form to validate. I don't understand:
Are the addValidator() arguments specific validators? Is there a list somewhere of those validators?
I've got this in the forms/contact.php:
class Application_Form_Contact extends Zend_Form
{
public function init()
{
$this->setAction('index/process');
$this->setMethod('post');
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Name:');
// $name->addValidator('alnum');
$name->setRequired(true);
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')->setRequired(true);
$confirm = new Zend_Form_Element_Text('confirm');
$confirm->setLabel('Confirm Email:')->setRequired(true);
$phone = new Zend_Form_Element_Text('phone');
$phone->setLabel('Phone:')->setRequired(true);
$subject = new Zend_Form_Element_Select('subject');
$subject->setLabel('Subject:')->setRequired(true);
$subject->setMultiOptions(array('Performance'=>'Performance',
'Workshop'=>'Workshop',
'Other'=>'Other'
));
$message = new Zend_Form_Element_Textarea('message');
$message->setLabel('Message:')->setRequired(true);
$message->setAttrib('rows','6');
$message->setAttrib('cols','30');
$submit = new Zend_Form_Element_Submit('Submit');
$this->addElements(array( $name,
$email,
$confirm,
$phone,
$subject,
$message,
$submit
));
$this->setElementDecorators(array
('ViewHelper',
array(array('data' => 'HtmlTag'), array('tag' => 'td')),
array('Label' , array('tag' => 'td')),
array(array('row' => 'HtmlTag') , array('tag' => 'tr'))
));
$submit->setDecorators(array('ViewHelper',
array(array('data' => 'HtmlTag'), array('tag' => 'td')),
array(array('emptyrow' => 'HtmlTag'), array('tag' => 'td', 'placement' => 'PREPEND')),
array(array('row' => 'HtmlTag') , array('tag' => 'tr'))
));
$this->setDecorators(array(
'FormElements',
array('HtmlTag' , array('tag' => 'table' , 'class' => 'formTable')),
'Form'
)
);
}
}
my controller is:
public function indexAction()
{
$this->view->form = new Application_Form_Contact();
}
public function processAction()
{
// $this->view->form = new Application_Form_Contact();
//
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
// echo 'success';
$this->view->data = $formdata;
} else {
// $form->populate($formData);
}
}
I'm a newbie, so I'm probably making some obvious errors that I don't see. I'm trying to do basic validation:
all fields must be filled out
all html gets stripped
email and confirm
email fields must match
email must be valid format.
Any help would be greatly appreciated!
Have you tried isValid() ?:
$form = new forms_ContactForm();
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
echo 'success';
exit;
} else {
$form->populate($formData);
}
}
$this->view->form = $form;
from
About the validators:
$firstName = new Zend_Form_Element_Text('firstName');
$firstName->setLabel('First name')
->setRequired(true)
->addValidator('NotEmpty');
$lastName = new Zend_Form_Element_Text('lastName');
$lastName->setLabel('Last name')
->setRequired(true)
->addValidator('NotEmpty');
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email address')
->addFilter('StringToLower')
->setRequired(true)
->addValidator('NotEmpty', true)
->addValidator('EmailAddress');
Heres the link to the Zend documentation about Zend fiorms and validators.
Creating Form Elements Using Zend_Form_Element