Hello,
I have two problems with sending emails.
I use Yii 2.0.32 and yii\swiftmailer\Mailer with SMTP.
-
My first problem is maybe related to the second. I have problems with the html emails, if I use
$m = $m->compose($view, $params);
then the content is complete missing. But it is rendered, if I believe the logs.
If I use
$m = $m->compose([‘html’ => $view, ‘text’ => ‘text/’.$view], $params);
then the content is only text, the html part is missing. -
The second problem is, that if I try to send two emails (one after the other) the first email has content, but the content in the second email is complete missing.
In the log there is logged that the views for both emails are rendered, but in the eml file of the second email there is only the header and no content.
Thank you very much for your help.
My Mailer class:
<?php
namespace project\helpers;
use Yii;
use yii\base\Component;
/**
* Mailer for sending e-mails to the user.
*/
class Mailer extends Component
{
/** @var string Path to the view files. */
public $viewPath = '@project/helpers/views/mail';
/**
* Send a message (mail).
* @param string $to
* @param string $subject
* @param string $view
* @param array $params
* @param array|null $attachment
* @param string|null $bcc
*/
public function sendMessage($to, $subject, $view, $params = [], $attachment = null, $bcc = null)
{
/** @var \yii\mail\BaseMailer $mailer */
$mailer = Yii::$app->mailer;
$mailer->viewPath = $this->viewPath;
$mailer->getView()->theme = Yii::$app->view->theme;
if (is_null($params)) {
$params = [];
}
$m = $mailer;
$m = $m->compose(['html' => $view, 'text' => 'text/'.$view], $params);
//$m = $m->compose($view, $params); // BUG empty content, this compose is only html with auto non-html, but html does not work in the other stmts so here not too => bam empty content?
// BUG then content is complete missing in email! the file is rendered (log):
//$m = $m->compose(['html' => $view], $params);
// BUG Rendering view file: /home/yanick/public_html/dev_env_yii2-all/vendor/projects/yii2-helpers/views/mail/terms-changed.php
// BUG but not in email...
$m->setTo($to);
if (!is_null($bcc)) {
$m->setBcc($bcc);
}
if (!is_null($attachment)) {
$m->attach($attachment[0], $attachment[1]);
}
$m->setFrom(Yii::$app->params['adminEmail'])
->setSubject($subject)
->send();
}
}
Mailer use:
// my Mailer class
$Mailer = new Mailer();
foreach ($users as $user) {
$Mailer->sendMessage(
$user->email,
'the terms changed',
'terms-changed',
[
'name' => $user->username,
]
);
}