Приветствую, форумчане.
Почему-то письма отправляются самому пользователю а не админу. Как перенастроить?
Смена 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>
I’m using basic Yii2 template and Swiftmailer to send email..
Here is my code for config/web.php:
'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',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'myemail@gmail.com',
'password' => 'password',
'port' => '587',
'encryption' => 'tls',
],
],
and my controller code is:
$fname = Yii::$app->request->post('fname');
$email = Yii::$app->request->post('email');
$industry = Yii::$app->request->post('industry');
$info = Yii::$app->request->post('info');
$mail = Yii::$app->mailer->compose()
->setFrom('myemail@gmail.com')
->setTo($email)
->setSubject('Test mail')
->setTextBody($info)
->send();
I’m getting email logs, but no email is being send…
Thanks.
За последние 24 часа нас посетили 8796 программистов и 846 роботов. Сейчас ищет 361 программист …
Yii2 Не приходит письмо на почту
Тема в разделе «Yii», создана пользователем Блэйд, 27 сен 2018.
-

- С нами с:
- 26 июл 2018
- Сообщения:
- 10
- Симпатии:
- 0
Всем привет! Расширенная версия yii2, с фронт и бекэнд. Установлен swiftmailer, и через фронтэнд (/frontend/письма приходят правильно, без проблем либо на почту, либо в папку /frontend/runtime/mail, как выберу.
Если создать отправку в консольном разделе — /console/, то письма приходят только /console/runtime/mail.
За отправку в папку/на почту отвечает параметр ‘useFileTransport’, и в main.php в разделе фронтэнда он стоит на false.
Работаю по видеоурокам и мой код должен работать, поскольку все идентично заведомо рабочему.Подскажите где искать проблему?
-
‘class’ => ‘yiiswiftmailerMailer’,
-
‘useFileTransport’ => false,
-
‘class’ => ‘Swift_SmtpTransport’,
-
‘host’ => ‘smtp.gmail.com’,
-
‘username’ => ‘rikzgt@gmail.com’,
-
$result = Yii::$app->mailer->compose(‘/mailer/newslist’, [
-
->setFrom(‘rikzgt@gmail.com’)
-
->setTo($subscriber[’email’])
-
->setSubject(‘Тема сообщения’)
-

- С нами с:
- 26 июл 2018
- Сообщения:
- 10
- Симпатии:
- 0
Проблема решена. Надо было отредактировать аналогично конфиг консоли — main-local.php
Автор видеоуроков данный момент не уточнил, и в инете эти «мелочи» не уточняются -

Команда форума
Модератор- С нами с:
- 20 июн 2012
- Сообщения:
- 8.490
- Симпатии:
- 1.731
Не надо видео-уроки. Есть же официальная дока, на русском языке: https://www.yiiframework.com/doc/guide/2.0/ru. И структура advanced-шаблона там описана, это три приложения в одном. Поэтому и конфиги разные. Хотя, есть и общие файлы, в них можно вынести.
Comments
sdlins
pushed a commit
to sdlins-forks/yii2
that referenced
this issue
Mar 3, 2015
sdlins
pushed a commit
to sdlins-forks/yii2
that referenced
this issue
Mar 3, 2015
sdlins
pushed a commit
to sdlins-forks/yii2
that referenced
this issue
Mar 7, 2015
sdlins
pushed a commit
to sdlins-forks/yii2
that referenced
this issue
Mar 7, 2015
sdlins
pushed a commit
to sdlins-forks/yii2
that referenced
this issue
Mar 7, 2015
sdlins
pushed a commit
to sdlins-forks/yii2
that referenced
this issue
Mar 7, 2015
sdlins
pushed a commit
to sdlins-forks/yii2
that referenced
this issue
Mar 8, 2015
sdlins
pushed a commit
to sdlins-forks/yii2
that referenced
this issue
Mar 8, 2015
sdlins
pushed a commit
to sdlins-forks/yii2
that referenced
this issue
Mar 8, 2015
sdlins
pushed a commit
to sdlins-forks/yii2
that referenced
this issue
Mar 8, 2015
#php #yii2 #swiftmailer
Вопрос:
Недавно я создал консольную команду в yii2 для массовой отправки электронных писем через запланированную задачу, код, который выполняет эту функцию, ранее включал ее в действие контроллера, чтобы это можно было сделать через Интернет.
Оказывается, электронные письма отлично отправляются через Интернет, но не через консоль. Я активировал журналы, чтобы посмотреть, не ошибка ли это, и я ничего не получаю, я даже ввел код, который увеличит счетчик, только если функция, отправляющая почту, возвращает true, и все же она всегда возвращает true.
Также бросьте, чтобы поймать исключения, и все же он не попадает ни в одно из них.
Правда в том, что я не знаю, что еще делать, я не хочу все время вводить данные, чтобы вручную отправлять электронные письма.
Мой код:
public function actionIndex()
{
try
{
// $check_enviados = Yii::$app->utiles->check_enviados();
// if (is_bool($check_enviados) === false)
// {
// // $this->stderr('Error: Limite maximo por hora alcanzado');
// return ExitCode::UNSPECIFIED_ERROR;
// }
$indicador_limite = false;
$programacion = ProgramacionEnvio::find()->one();
if (!$programacion)
{
// $this->stderr('Error: No hay envios pendientes');
return ExitCode::UNSPECIFIED_ERROR;
}
$user = $programacion->proen_usuario_creador;
// Iniciamos el componente para enviar el correo
$message = Yii::$app->mailer->compose();
// Indicamos el correo principal
$message->setFrom([Yii::$app->params['adminEmail'] => Yii::$app->params['senderName']]);
// Se coloca el titulo indicado por la persona en el formulario
$message->setSubject($programacion->proen_titulo);
// Se inicializa la clase DOM para incrustar las imagenes subidas en el editor y se puedan ver en el correo
$dom = new DOMDocument();
// Cargamos el contenido realizado en el editor
$dom->loadHTML($programacion->proen_contenido);
// Procedemos a buscar las imagenes
$images = $dom->getElementsByTagName('img');
foreach ($images as $image)
{
// Obtenemos la antigua URL para luego obtener el nombre del archivo
$old_src = $image->getAttribute('src');
// Se obtiene el nombre del archivo
$imgname = basename($old_src);
// Se indica la ruta donde esta ubicada
$imgroute = Yii::getAlias('@app/web/images/tmp/').$user."/".$imgname;
if (file_exists($imgroute))
{
// Se procede a incrustar las imagenes
$new_src = $message->embed($imgroute);
// Del codigo generado se cambia el SRC de la imagen por el generado
$image->setAttribute('src', $new_src);
}
}
$message->setHtmlBody($dom->saveHTML());
$adjuntos = AdjuntosProgramacion::find()->where(['proen_id'=>$programacion->proen_id])->all();
if ($adjuntos)
{
$path = Yii::getAlias('@app/web/tmpfiles/').$user."/";
if (file_exists($path))
{
$noencontrado = false;
foreach ($adjuntos as $adjunto)
{
if (file_exists($path.$adjunto->adpro_nombre))
{
$message->attach($path.$adjunto->adpro_nombre);
}
}
}
}
// $contactos = Contacto::find()->where(['>','con_id',$programacion->proen_ultimo_id_enviado])->limit(10)->all();
// foreach ($contactos as $index => $contacto)
// {
// // $check_enviados = Yii::$app->utiles->check_enviados();
// // if (is_bool($check_enviados) === false)
// // {
// // $indicador_limite = true;
// // break;
// // }
// $message->setTo($contacto->con_email);
// if ($message->send())
// {
// Yii::$app->utiles->update_contador_hora();
// $programacion = ProgramacionEnvio::findOne($programacion->proen_id);
// $programacion->proen_ultimo_id_enviado = $contacto->con_id;
// $programacion->proen_ultimo_envio = date('Y-m-d H:i:s');
// $programacion->proen_enviados = $programacion->proen_enviados 1;
// $programacion->save();
// }
// }
// $message->setTo('darknightedm@gmail.com');
$message->setTo('esp.ernesto1@gmail.com');
var_dump($message->send());exit;
// if (Yii::$app->mailer->getSwiftMailer()->send($message->getSwiftMessage(), $failures))
// {
// var_dump($failures);
// }
// if (Contacto::find()->count() == $programacion->proen_enviados)
// {
// AdjuntosProgramacion::deleteAll(['proen_id'=>$programacion->proen_id]);
// $programacion->delete();
// }
// if ($indicador_limite === true)
// {
// // $this->stderr('Error: Limite maximo por hora alcanzado');
// return ExitCode::UNSPECIFIED_ERROR;
// }
// $this->stderr('Se enviaron los correos exitosamente');
return ExitCode::OK;
}
catch (Exception $e)
{
$this->stderr("Ocurrió el siguiente error: {$e->getMessage()}");
return ExitCode::UNSPECIFIED_ERROR;
}
catch(Swift_TransportException $s)
{
$this->stderr("Ocurrió el siguiente error: {$s->getMessage()}");
return ExitCode::UNSPECIFIED_ERROR;
}
}
Моя консоль.конфигурация:
<?php
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'appcommands',
'timezone' => 'America/Caracas',
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
'@tests' => '@app/tests',
'@tmpimages' => 'images/tmp/'
],
'components' => [
'cache' => [
'class' => 'yiicachingFileCache',
],
'log' => [
'targets' => [
[
'class' => 'yiilogFileTarget',
'levels' => ['error', 'warning'],
'categories' => ['yiiswiftmailerLogger::add'],
'logFile' => '@app/runtime/logs/email.log',
],
],
],
'mailer' => [
'class' => 'yiiswiftmailerMailer',
'enableSwiftMailerLogging' => true,
// 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,
'transport' => [
'class' => 'Swift_SmtpTransport',
// 'host' => 'smtp.gmail.com',
// 'username' => 'xxxxxxx@gmail.com',
// 'password' => 'xxxxxxx',
// 'port' => '587',
// 'encryption' => 'tls',
'host' => 'mail.telectronicavalero.com',
'username' => 'xxxxxxxx@telectronicavalero.com',
'password' => 'xxxxxxxx',
'port' => '25',
// 'encryption' => 'tls',
'plugins'=> [
// [
// 'class' => 'Swift_Plugins_ThrottlerPlugin',
// 'constructArgs' => ['20'],
// ],
[
'class' => 'Swift_Plugins_AntiFloodPlugin',
'constructArgs' => [50,3],
],
],
],
],
'utiles' => [
'class' => 'appcomponentsUtiles',
],
'db' => $db,
],
'modules'=>[
'user-management' => [
'class' => 'webvimarkmodulesUserManagementUserManagementModule',
'controllerNamespace'=>'vendorwebvimarkmodulesUserManagementcontrollers', // To prevent yii help from crashing
],
],
'params' => $params,
/*
'controllerMap' => [
'fixture' => [ // Fixture generation command line.
'class' => 'yiifakerFixtureController',
],
],
*/
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yiigiiModule',
];
}
return $config;
My action in a web controller to test the code:
public function actionEnviarcorreos()
{
// $check_enviados = Yii::$app->utiles->check_enviados();
// if (is_bool($check_enviados) === false)
// {
// Yii::$app->session->setFlash('error', "Se ha alcanzado el limite de correos enviados por hora, puede volver a enviar mensajes despues de: {$check_enviados}.");
// return $this->redirect(['index']);
// }
// Se obtiene el nombre del usuario
$user = Yii::$app->user->identity->username;
$indicador_limite = false;
$contador_enviados = 0;
// $programacion = ProgramacionEnvio::findOne($id);
$programacion = ProgramacionEnvio::find()->one();
if (!$programacion)
{
Yii::$app->session->setFlash('error', "No se ha encontrado la programacion.");
return $this->redirect(['index']);
}
// Iniciamos el componente para enviar el correo
$message = Yii::$app->mailer->compose();
// Indicamos el correo principal
$message->setFrom([Yii::$app->params['adminEmail'] => Yii::$app->params['senderName']]);
// Se coloca el titulo indicado por la persona en el formulario
$message->setSubject($programacion->proen_titulo);
// Se inicializa la clase DOM para incrustar las imagenes subidas en el editor y se puedan ver en el correo
$dom = new DOMDocument();
// Cargamos el contenido realizado en el editor
$dom->loadHTML($programacion->proen_contenido);
// Procedemos a buscar las imagenes
$images = $dom->getElementsByTagName('img');
foreach ($images as $image)
{
// Obtenemos la antigua URL para luego obtener el nombre del archivo
$old_src = $image->getAttribute('src');
// Se obtiene el nombre del archivo
$imgname = basename($old_src);
// Se indica la ruta donde esta ubicada
$imgroute = Yii::getAlias('@app/web/images/tmp/').$user."/".$imgname;
if (file_exists($imgroute))
{
// Se procede a incrustar las imagenes
$new_src = $message->embed($imgroute);
// Del codigo generado se cambia el SRC de la imagen por el generado
$image->setAttribute('src', $new_src);
}
}
$message->setHtmlBody($dom->saveHTML());
$adjuntos = AdjuntosProgramacion::find()->where(['proen_id'=>$id])->all();
if ($adjuntos)
{
$path = Yii::getAlias('@app/web/tmpfiles/').$user."/";
if (file_exists($path))
{
$noencontrado = false;
foreach ($adjuntos as $adjunto)
{
if (file_exists($path.$adjunto->adpro_nombre))
{
$message->attach($path.$adjunto->adpro_nombre);
}
elseif (!file_exists($path.$adjunto->adpro_nombre) amp;amp; $noencontrado === false)
{
Yii::$app->session->setFlash('warning', "Algunos archivos adjuntos relacionados a este contenido no se encontraron.");
}
}
}
else
{
Yii::$app->session->setFlash('warning', "El correo debía contener archivos adjuntos, sin embargo, estos no se encontraron.");
}
}
$contactos = Contacto::find()->where(['>','con_id',$programacion->proen_ultimo_id_enviado])->limit(250)->all();
foreach ($contactos as $contacto)
{
// $check_enviados = Yii::$app->utiles->check_enviados();
// if (is_bool($check_enviados) === false)
// {
// $indicador_limite = true;
// break;
// }
$message->setTo($contacto->con_email);
if ($message->send())
{
Yii::$app->utiles->update_contador_hora();
$programacion = ProgramacionEnvio::findOne($programacion->proen_id);
$programacion->proen_ultimo_id_enviado = $contacto->con_id;
$programacion->proen_ultimo_envio = date('Y-m-d H:i:s');
$programacion->proen_enviados = $programacion->proen_enviados 1;
$programacion->save();
}
}
if (Contacto::find()->count() == $programacion->proen_enviados)
{
AdjuntosProgramacion::deleteAll(['proen_id'=>$programacion->proen_id]);
$programacion->delete();
}
if ($indicador_limite === true)
{
Yii::$app->session->setFlash('error', "Se enviaron algunos correos, pero se ha alcanzado el limite de correos enviados por hora, puede volver a enviar mensajes despues de: {$check_enviados}.");
}
else
{
Yii::$app->session->setFlash('success', "Se ha enviado el correo con exito");
}
return $this->redirect(['index']);
}
Thanks for your attention, greetings.
i’m trying to send a mail. i want to use Gmail server to send, for now i just want it to send to the same account from its being sent.
i’m using YiiMailer extension because it seems to be easy to use, this is the action i have in my controller:
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->subject).'?=';
$headers="From: $name <{$model->email}>rn".
"Reply-To: {$model->email}rn".
"MIME-Version: 1.0rn".
"Content-Type: text/plain; charset=UTF-8";
// mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
$mail = new YiiMailer('contact', array(
'message'=>$model->body,
'name'=>$model->name,
'description'=>'Contact form'
));
$mail->setFrom($model->email, $model->name);
$mail->setSubject($model->subject);
$mail->setTo(Yii::app()->params['adminEmail']);
$mail->isSMTP();
$mail->host = "smtp.gmail.com";
$mail->port = 465;
$mail->Username = "username@gmail.com";
$mail->Password = "password";
if($mail->send())
{
Yii::app()->user->setFlash('contact','Gracias por contactarnos, te responderemos tan pronto como podamos.');
$this->refresh();
}
else
{
Yii::app()->user->setFlash('error','Error enviando correo.');
$this->refresh();
}
}
}
$this->render('contact',array('model'=>$model));
}
the adminMail is the same like account@gmail.com
i dont’t know if i have the right settings for gmail, i’m sure the condition of the function doesn’t exist so it does nothing.
just to make sure. this is my config:
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
'ext.YiiMailer.YiiMailer'
),
PD: i found the gmail settings around post. i’m not sure if they changed the settings.