Yii2 отправка почты ошибка

Контроллер

public function actionIndex(){
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

Модель

public function contact($email)
    {
        if ($this->validate()) {
            Yii::$app->mailer->compose()
                ->setTo($email)
                ->setFrom([$this->email => $this->name])
                ->setSubject($this->subject)
                ->setTextBody($this->body)
                ->send();

            return true;
        } else {
            return false;
        }
    }

Форма

<?php $form = ActiveForm::begin(['id' => 'contact-form', 'options' => ['class' => 'contact ']]); ?>
                <?= $form->field($model, 'name')->label(false)->textInput(array('placeholder' => 'Представьтесь')) ?>
                <?= $form->field($model, 'email')->label(false)->textInput(array('placeholder' => 'Обратная связь (почта, skype, телефон)'))?>
                <?= $form->field($model, 'body')->textArea(['rows' => 6])->label(false)->textarea(array('placeholder' => 'Ваше сообщение'))?>
                <div class="form-group">
                    <?= Html::submitButton('Отправить', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
                </div>
                <?php ActiveForm::end(); ?>

Ошибка

Приветствую, форумчане.

Почему-то письма отправляются самому пользователю а не админу. Как перенастроить?
Смена setTo на setFrom не срабатывает.

Controller — IndexController (extends AppController)
Форма -СontactForm
Вид — views/index/contact.php

ContactForm

Код: Выделить всё

<spoiler title="">
<?php

namespace appmodels;

use Yii;
use yiidbActiveRecord;
use yiidbExpression;


error_reporting(E_ALL);
 /**
 * This is the model class for table "contactform".
 *
 * @property string $id
 * @property string $name
 * @property string $email
 * @property integer $subject
 * @property double $body
 * @property string $verifyCode
 
 */

class Contactform extends ActiveRecord
{
    public $id;
    public $name;
    public $email;
    public $subject;
    public $body;
    public $verifyCode;


     public static function tableName()
    {
        return 'contactform';
    }
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
       
           /* Поля обязательные для заполнения */
            [ ['name', 'email', 'subject', 'body'], 'required'],
            /* Поле электронной почты */
            ['email', 'email'],
            /* Капча */
            ['verifyCode', 'captcha', 'captchaAction'=>'index/captcha'],
          /*  ['verifyCode', 'captcha','captchaAction'=>'/contactus/default/captcha'],*/

        ];

    }

    /**
     * @return array customized attribute labels
     */
    public function attributeLabels()
    {
        return [
            'verifyCode' => 'Подтвердите код',
            'name' => 'Имя',
            'email' => 'Электронный адрес',
            'subject' => 'Тема',
            'body' => 'Сообщение',
        ];
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     * @param  string  $email the target email address
     * @return boolean whether the model passes validation
     */
   
     
  

         public function contact($adminEmail)
    {
        if ($this->validate()) {
          
             Yii::$app->mailer->compose()
            ->setFrom(Yii::$app->params['adminEmail']) /* от кого */
            ->setTo([$this->email => $this->name]) 
            // ->setFrom([$this->email => $this->name]) 
           //  ->setFrom(Yii::$app->params['adminEmail']) 
         //   ->setTo($adminEmail)
           //    ->setFrom([$this->email => $this->name])
              //  ->setTo([$this->email => $this->name])
             //  ->setFrom ($adminEmail)
            //  ->setTo([$adminEmail])
            //  ->setFrom ([$this->email => $this->name]) 
             //  ->setFrom([$this->email => $this->name]) 

            // ->setTo(['medeyacom@mail.ru' => $this->name])
            //->setTo($adminEmail)
             
              ->setSubject($this->subject) /* имя отправителя */
              ->setTextBody($this->body) /* текст сообщения */
               ->send();

              return true;
             } 
          return false;
            
        
    }
                   
 }               






</spoiler>

config/web

Код: Выделить всё

<spoiler title="">
  'mailer' => [
         'class' => 'yiiswiftmailerMailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => false, //если false то письма будут отпр. если true то в папке runtime 
            'transport'=>[
                'class' => 'Swift_SmtpTransport',     
                'host' => 'smtp.mail.ru',
                'port' => '465', // для mail.ru
                'encryption' => 'ssl', // tls
                'username' => 'username@mail.ru',
                'password' => 'password',
                
              // 'host' => 'smtp.gmail.com',
              /* 'options' => array('hostname' => 'smtp.gmail.com',*/
             //   'username' => 'username@gmail.com',
             //   'password' => 'password',
             //   'port' => '25',
             //   "encryption" => ("tls"),
               // 'viewPath' => '@common/mail',
            ],
        ],

</spoiler>

IndexController

Код: Выделить всё

<spoiler title="">
<?php


namespace appcontrollers;

use Yii;
use yiiAppController;
use appmodelsContactForm;
use yiiwebRequest;




class IndexController extends AppController
{


  public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yiicaptchaCaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ]
        ];
    }
    public function actionContact()
        {
        $model = new ContactForm();
        /*if ($model->load(Yii::$app->request->post()) && $model->contact(setting::ADMIN_EMAIL_ADDRESS))*/
         if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail']))
         {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }   
    

  

   
}
    

 
</spoiler>


SiteControler

Код: Выделить всё

<spoiler title="">
<?php

namespace appcontrollers;

use Yii;
use yiifiltersAccessControl;
use yiiwebController;
use yiifiltersVerbFilter;
use appmodelsLoginForm;
use appmodelsContactForm;
//use appmodelsMailerForm;

class SiteController extends Controller
{
     public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        //'actions' => ['logout'],
                        'actions' => ['captcha','index','logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post','get'],
                ],
            ],
        ];
    }

    
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yiiwebErrorAction',
            ],
            'captcha' => [
                'class' => 'yiicaptchaCaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

  

    public function actionIndex()
    {
       $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(setting::ADMIN_EMAIL_ADDRESS)) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        } else {
            return $this->render('default', [
                'model' => $model,
            ]);
        }
    }

   

    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

   public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }

    public function actionAbout()
    {
        return $this->render('about');
    }

  /*  public function actionMailer()
    {
        $model = new MailerForm();
        if ($model->load(Yii::$app->request->post()) && $model->sendEmail()) {
            Yii::$app->session->setFlash('mailerFormSubmitted');
            return $this->refresh();
        }
          return $this->render('mailer', [
              'model' => $model,
          ]);
    }*/

}

    



</spoiler>

Проблема в настройках сервера, нужно смотреть, в логах что происходит при отправке письма tail -f /var/log/syslog.

Лучше используй SMTP сервер, так больше вероятности, что твое письмо не улетит в SPAM:

'mailer' => [
    'useFileTransport' => false,
    'messageConfig' => [
        'charset' => 'UTF-8',
    ],
    'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'smtp.google.com',
        'username' => 'your_email@gmail.com',
        'password' => '*********',
        'port' => '465',
    ],
],

I’m using yii2 and I’m totally new to this can someone help me with sending emails in this framework I’m using swiftmailer and have set the configurations as:

'mailer' => [
        'class' => 'yiiswiftmailerMailer',
        'useFileTransport' => false,
]

asked May 11, 2015 at 12:37

Susreetha eks's user avatar

'mailer' => [
        'class' => 'yiiswiftmailerMailer',
        'useFileTransport'=>false,
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.gmail.com',
            'username' => 'test@gmail.com',
            'password' => 'password',
            'port' => '465',
            'encryption' => 'ssl',
        ],
    ],

Add these lines to config/main.php.
Make a view for your mail body and give path to that view in below function
and use that code you want to send the mail

$check=Yii::$app->mailer->compose('../../frontend/views/mail',  ['data'=> 'Mail data'])
        ->setFrom('test@gmail.com')
        ->setTo('testsent@gmail.com')
        ->setSubject('check sending mail')
        ->send();
    var_dump($check);

answered Sep 7, 2015 at 9:36

Anway Kulkarni's user avatar

You need to configure the transport correctly

In this example i suppose you use gmail, if this is not true you need change the values with your values.

    'mailer' => [
        'class' => 'yiiswiftmailerMailer',
        'viewPath' => '@common/mail',
        'useFileTransport' => false,
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.gmail.com',
            'username' => 'yourName@gmail.com',
            'password' => 'yourPassword',
            'port' => '587',
            'encryption' => 'tls',
        ],
    ],

answered May 11, 2015 at 13:11

ScaisEdge's user avatar

ScaisEdgeScaisEdge

132k10 gold badges90 silver badges105 bronze badges

4

add below code in your common->config->main-local.php file under components section:

'mailer' => [
    'class' => 'yiiswiftmailerMailer',
    'viewPath' => '@common/mail',
    'useFileTransport' => false,
    'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'smtp.gmail.com',
        'username' => 'your@email.com',
        'password' => 'password',
        'port' => '465',
        'encryption' => 'ssl',
    ],
],

node_modules's user avatar

node_modules

4,7606 gold badges21 silver badges37 bronze badges

answered Mar 16, 2017 at 11:57

Hunny's user avatar

HunnyHunny

315 bronze badges

Please check your port this was my problem when i worked with mailer in yii2

answered Oct 24, 2017 at 9:16

Karim Haddad's user avatar

Recently started using Yii2 and the time has come to introduce mailing features to the project. I also needed auth features on the project so decided to try out «dektrium/yii2-user» package. It requires configured Swiftmailer, so:

main-local.php:
‘components’=>[
‘mail’ => [
‘class’ => ‘yiiswiftmailerMailer’,
‘useFileTransport’ => false,
‘transport’ => [
‘class’ => ‘Swift_SmtpTransport’,
‘host’ => ‘smtp.gmail.com’,
‘username’ => ‘account@gmail.com’,
‘password’ => ‘password’,
‘port’ => ‘465’,
‘encryption’ => ‘ssl’,
],
],

],

Seems like a very trivial situation, but the email simply does not send.
First, I tried changing the ‘port’ and ‘encryption’ value, since in the past gmail was quite strict with the connection rules — no luck.
Tried ‘port’ values: ‘465’, ‘587’, ’25’.
Tried ‘encryption’ values: ‘ssl’,’tls’. Additionally tried accessing ‘host’=>’tls://smtp.gmail.com’ while commenting out ‘encryption’ line. Also no luck.
Moreover, it is not just ‘dektrium/yii2-user’ package which is not sending emails, I tried to do a manual send of a simple test email from a controller — no luck.

After reviewing the Debugger information provided, it seems that the e-mail is generated perfectly fine every time, I can even download it from the Debugger — however, «Successfully sent» is always «No» on the Mail tab of the request. Log doesn’t seem to be providing any information as to what happened, as no explicit warnings/errors are received — the email is simply not sending.

I am quite new to Yii and programming in general, so I may have missed something, but I am spending way too much time on trying to resolve an issue which I cannot find any information about..

Waiting for your professional advice! Thanks in advance.

P.S. ‘dektrium/yii2-user’ has a variable for SentFrom hardcoded in the module — I had to change this value to the real gmail account the sending would be from in order to eliminate potential From: injection restriction.

  • Yii2 вывести сообщение об ошибке
  • Yesterday i get up very early текст содержит разные ошибки
  • Yes of course not ошибка
  • Yealink zadarma ошибка регистрации
  • Yealink w52p ошибка регистрации трубки