Yii отправка почты

1. Необходимое расширение http://www.yiiframework.com/extension/smtp-mail/
ложить в extensions

2. \protected\config\main.php

    'components' => array(    
        'Smtpmail' => array(
            'class' => 'application.extensions.smtpmail.PHPMailer',
            'Host' => '***', //имя Smtp сервера
            'Username' => '',
            'Password' => '',
            'Mailer' => 'smtp',
            'Port' => 25,
            'SMTPDebug' => 1,
        ),
3. \protected\models\ContactForm.php

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'),
            array('name,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(
            'name' => 'имя пользователя',
            'body' => 'текст сообщения',
                //'verifyCode'=>'Verification Code',
        );
    }

}

4. \protected\controllers\SiteController.php

    public function mailsend($to, $from, $subject, $message)
    {
        $mail = Yii::app()->Smtpmail;
        $mail->SetFrom('robot@site.ru', $from);   //от кого
        $mail->Subject = $subject;
        //$mail->SetLanguage("ru","phpmailer/language"); 
        $mail->CharSet = "utf-8";
        //$message = iconv("Windows-1251", "UTF-8", $message);
        $mail->MsgHTML(mb_convert_encoding($message, "UTF-8", "auto"));
        $mail->AddAddress($to, "");

        if (!$mail->Send())
        {
            Yii::app()->user->setFlash("Mailer Error: ", $mail->ErrorInfo);
        }
        else
        {
            Yii::app()->user->setFlash('contact', 'Сообщение отправлено');
            $this->refresh();
        }
        $mail->ClearAddresses();
    }

    /**
     * Displays the contact page
     */
    public function actionContact()
    {
        $model = new ContactForm;
        if (isset($_POST['ContactForm']))
        {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate())
            {
                /*   $name = '=?UTF-8?B?' . base64_encode($model->name) . '?=';
                  $subject = '=?UTF-8?B?' . base64_encode($model->name) . '?=';
                  $headers = "From: $name <{$model->name}>\r\n" .
                  "Reply-To: {$model->name}\r\n" .
                  "MIME-Version: 1.0\r\n" .
                  "Content-Type: text/plain; charset=UTF-8";

                  //send_email($model->body, $model->name);
                  mail(Yii::app()->params['adminEmail'], $subject, $model->body, $headers);
                  Yii::app()->user->setFlash('contact', 'Сообщение отправлено_'.$model->name);
                  $this->refresh(); */

                //SiteController::send_email($model->name, $model->body );
                $this->mailsend(Yii::app()->params['adminEmail'], $model->name, 'support', $model->body);
            }
        }
        $this->render('contact', array('model' => $model));
    }

5. \protected\views\site\contact.php


<?php
/* @var $this SiteController */
/* @var $model ContactForm */
/* @var $form CActiveForm */

$this->pageTitle = Yii::app()->name . ' - Contact Us';
$this->breadcrumbs = array(
    'Contact',
);
?>

<h1>Contact Us</h1>

<?php if (Yii::app()->user->hasFlash('contact')): ?>

    <div class="flash-success">
        <?php echo Yii::app()->user->getFlash('contact'); ?>
    </div>

<?php else: ?>

    <p>
        If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
    </p>

    <div class="form">

        <?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.</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>

        <?php $this->endWidget(); ?>

    </div><!-- form -->

<?php endif; ?>

Комментарии

Популярные сообщения из этого блога

Пишем логи на C# (.NET). Легкий способ.

Учебник yii2

Автоматический вход пользователя на сервер посредством putty (протокол SSH)