Fail To Send Email To Admin From 'contact Form'

Hi, I am just start learn how to use Yii Framework for my current project. I am facing a problem to send an email to admin after I fill out all the details on the ‘Contact Form’. I have already change the ‘adminEmail’ to my email address from the protected/config/main.php.

Here’s my code:

[color="#FF0000"]protected/model/ContactForm:[/color]

class ContactForm extends CFormModel

{

public $name;


public $email;


public $subject;


public $body;


public $verifyCode;





public function rules()


{


	return array(


		// name, email, subject and body are required


		array('name, email, subject, body', 'required'),


		// email has to be a valid email address


		array('email', 'email'),


		// verifyCode needs to be entered correctly


		array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),


	);


}





public function attributeLabels()


{


	return array(


		'verifyCode'=>'Verification Code',


	);


}

}

[color="#FF0000"]protected/controllers/SiteController.php:[/color]

public function actionContact()

{


	$model=new ContactForm;


	if(isset($_POST['ContactForm']))


	{


		$model->attributes=$_POST['ContactForm'];


		if($model->validate())


		{


		   $message = 'Hello World!';


           $mailer = Yii::createComponent('application.extensions.mailer.EMailer');


           //$mailer->Host = 'localhost';


           $mailer->IsSMTP();


       $mailer->IsHTML(true);


           $mailer->SMTPAuth = true;


           $mailer->SMTPSecure = "ssl";


           $mailer->Host = "smtp.gmail.com";


           $mailer->Port = 465;


           $mailer->From = $model->email;


           $mailer->AddReplyTo($model->email);


           $mailer->AddAddress(Yii::app()->params['adminEmail']);


           $mailer->FromName = $model->name;


           $mailer->CharSet = 'UTF-8';


           $mailer->Subject = $model->subject;


           $mailer->Body = $message;


           $mailer->Send();

Yii::app()->user->setFlash(‘contact’,‘Thank you for contacting us. We will respond to you as soon as possible.’);

			$this->refresh();


		}


	}


	$this->render('contact',array('model'=>$model));


}

Does anyone knows how to solve it? I need help~ Thanks in advance :rolleyes:

do you get an error?

Hi, thanks for the reply and help. No, there is no error. But when i check my gmail mailbox (admin email), there is no email that has been sent.

Here’s my code for [color="#FF0000"]protected/config/main.php:[/color]

// application components

'components'=>array(


    'mailer' => array(


    'class' => 'application.extensions.mailer.EMailer',


    'pathViews' => 'application.views.email',


    'pathLayouts' => 'application.views.email.layouts'


    ),


	'user'=>array(


		// enable cookie-based authentication


		'allowAutoLogin'=>true,


	),

Please help me~~

well I wanna help you. But I would not know unless there is an error everything seems to be okay in terms of syntax I don’t see anything wrong with logic either


// does it display the message in your view

Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');

$this->refresh();

Hi, alirz23. Thank you so much for ur help. Ya, it does display message in my view. But im wondering why it does not send any email to my gmail mailbox since there is no error and everything seems okay. Did I miss out anything? or did I use any wrong port number??

the port number is right gmail uses 465 by default I don’t see anything wrong with your code, could be your network

or try a different extension

Hi, alirz23. I have tried another extension which is YiiMailer and here’s the link that I followed step by step on how to install it.

YiiMailer extension

And here’s my code:

[color="#FF0000"]protected/config/main.php[/color]




...

'import'=>array(

	    'ext.YiiMailer.YiiMailer',

		'application.models.*',

		'application.components.*',

	),



[color="#FF0000"]protected/config/mail.php[/color]




<?php

return array(

    'viewPath' => 'application.views.mail',

    'layoutPath' => 'application.views.layouts',

    'baseDirPath' => 'webroot.images.mail',

    'savePath' => 'webroot.assets.mail',

    'testMode' => false,

    'layout' => 'mail',

    'CharSet' => 'UTF-8',

    'AltBody' => Yii::t('YiiMailer','You need an HTML capable viewer to read this message.'),

    'language' => array(

		'authenticate'         => Yii::t('YiiMailer','SMTP Error: Could not authenticate.'),

		'connect_host'         => Yii::t('YiiMailer','SMTP Error: Could not connect to SMTP host.'),

		'data_not_accepted'    => Yii::t('YiiMailer','SMTP Error: Data not accepted.'),

		'empty_message'        => Yii::t('YiiMailer','Message body empty'),

		'encoding'             => Yii::t('YiiMailer','Unknown encoding: '),

		'execute'              => Yii::t('YiiMailer','Could not execute: '),

		'file_access'          => Yii::t('YiiMailer','Could not access file: '),

		'file_open'            => Yii::t('YiiMailer','File Error: Could not open file: '),

		'from_failed'          => Yii::t('YiiMailer','The following From address failed: '),

		'instantiate'          => Yii::t('YiiMailer','Could not instantiate mail function.'),

		'invalid_address'      => Yii::t('YiiMailer','Invalid address'),

		'mailer_not_supported' => Yii::t('YiiMailer',' mailer is not supported.'),

		'provide_address'      => Yii::t('YiiMailer','You must provide at least one recipient email address.'),

		'recipients_failed'    => Yii::t('YiiMailer','SMTP Error: The following recipients failed: '),

		'signing'              => Yii::t('YiiMailer','Signing Error: '),

		'smtp_connect_failed'  => Yii::t('YiiMailer','SMTP Connect() failed.'),

		'smtp_error'           => Yii::t('YiiMailer','SMTP server error: '),

		'variable_set'         => Yii::t('YiiMailer','Cannot set or reset variable: ')

    ),

);



[color="#FF0000"]protected/controllers/SiteController.php[/color]




...

public function actionContact()

	{

		$model=new ContactForm;

		if(isset($_POST['ContactForm']))

		{

			$model->attributes=$_POST['ContactForm'];

			if($model->validate())

			{	

				//use 'contact' view from views/mail

		        $mail = new YiiMailer('contact', array('message' => $model->body, 'name' => $model->name, 'description' => 'Contact form'));

				

				//set properties

				$mail->setFrom($model->email, $model->name);

				$mail->setSubject($model->subject);

				$mail->setTo(Yii::app()->params['adminEmail']);

				//send

				if ($mail->send()) {

					Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');

				} else {

					Yii::app()->user->setFlash('error','Error while sending email: '.$mail->getError());

				}

				

				$this->refresh();

			}

		}

		$this->render('contact',array('model'=>$model));

	}



[color="#FF0000"]protected/views/mail/contact.php[/color]




....

?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'contact-form',

	'enableClientValidation'=>true,

	'clientOptions'=>array(

		'validateOnSubmit'=>true,

	),

)); ?>


	<p class="note">Fields with <span class="required">*</span> are required to fill out.</p>


	<?php echo $form->errorSummary($model); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'name'); ?>

		<?php echo $form->textField($model,'name'); ?>

		<?php echo $form->error($model,'name'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'email'); ?>

		<?php echo $form->textField($model,'email'); ?>

		<?php echo $form->error($model,'email'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'subject'); ?>

		<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?>

		<?php echo $form->error($model,'subject'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'body'); ?>

		<?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?>

		<?php echo $form->error($model,'body'); ?>

	</div>


	<?php if(CCaptcha::checkRequirements()): ?>

	<div class="row">

		<?php echo $form->labelEx($model,'verifyCode'); ?>

		<div>

		<?php $this->widget('CCaptcha'); ?>

		<?php echo $form->textField($model,'verifyCode'); ?>

		</div>

		<div class="hint">Please enter the letters as they are shown in the image above.

		<br/>Letters are not case-sensitive.</div>

		<?php echo $form->error($model,'verifyCode'); ?>

	</div>

	<?php endif; ?>


	<div class="row buttons">

		<?php echo CHtml::submitButton('Submit'); ?>

	</div>



[color="#FF0000"]protected/models/ContactForm.php[/color]




class ContactForm extends CFormModel

{

	public $name;

	public $email;

	public $subject;

	public $body;

	public $verifyCode;


	/**

	 * Declares the validation rules.

	 */

	public function rules()

	{

		return array(

			// name, email, subject and body are required

			array('name, email, subject, body', 'required'),

			// email has to be a valid email address

			array('email', 'email'),

			// verifyCode needs to be entered correctly

			array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),

		);

	}


	/**

	 * Declares customized attribute labels.

	 * If not declared here, an attribute would have a label that is

	 * the same as its name with the first letter in upper case.

	 */

	public function attributeLabels()

	{

		return array(

			'verifyCode'=>'Verification Code',

		);

	}

}

 



However, it returns the error: ‘Undefined variable: model’. Please help me. Thanks in advance.

I believe you need to send model to the email view as well since you have a reference to $model in your mail/view


//use 'contact' view from views/mail

$mail = new YiiMailer('contact', array('message' => $model->body, 'name' => $model->name, 'description' => 'Contact form', 'model'=>$model));

Ya, you are right! I just realized that a few minutes ago. Thanks for correcting me. I changed the ‘YiiMailer’ into ‘ContactForm’ but it returns another error which is 'ContactForm and its behaviors do not have a method or closure named “setFrom”. ’ And I do not understand the error. :mellow:

[color="#FF0000"]\framework\base\CComponent.php(line 266) :[/color]




public function __call($name,$parameters)

	{

		if($this->_m!==null)

		{

			foreach($this->_m as $object)

			{

				if($object->getEnabled() && method_exists($object,$name))

					return call_user_func_array(array($object,$name),$parameters);

			}

		}

		if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)

			return call_user_func_array($this->$name, $parameters);

		throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',

			array('{class}'=>get_class($this), '{name}'=>$name)));

	}



after this code implement i got a error like

----View "contact" not found—

yes…i got it…

I prefer you use this extension, it’s work for me fine…

Put in your config (main.php)-


'Smtpmail'=>array(

            'class'=>'application.extensions.smtpmail.PHPMailer',

            'Host'=>"smtp.gmail.com",

            'Username'=>'your_email_id@gmail.com',

            'Password'=>'******',

            'Mailer'=>'smtp',

            'Port'=>587,

            'SMTPAuth'=>true, 

	    'SMTPSecure' => 'tls',

        ),



Your mail sending code (Put in your view or controller as per the use) -




$to = 'demo@example.com'; //Email id, which you want to send an email

$from= 'your_email_id@gmail.com'; //Email id, provide your email id


$mail=Yii::app()->Smtpmail;

$mail->SetFrom($from, 'Yii Demo');

$mail->Subject = 'your email subject';

$mail->MsgHTML('Testing...');

$mail->AddAddress($to, "");

$mail->IsHTML(true);

$mail->Send();

Extension Link - http://www.yiiframework.com/extension/smtp-mail/

[/quote]