1

I've been struggling to make this work within a plugin. I have a html file in my templates folder called _email.html. I try to load it in my plugin but then I get an error. This is my code:

Craft::$app->mailer->compose('_email.html', ['body' => $emailBody])
            ->setFrom($fromMail)
            ->setTo($toMail)
            ->setSubject($subject)
            ->send();

The problem is that the Yii mailer is looking in the vendor folder instead of the templates folder.

This is the error I get:

The view file does not exist: /Applications/MAMP/htdocs/project/vendor/craftcms/cms/src/mail/_email

Even when I try going back to the templates folder it doesn't seem to work and I get the following error:

The view file does not exist: /Applications/MAMP/htdocs/project/vendor/craftcms/cms/src/mail/../../../../../../templates/_email

I found out that if I copy and paste the contents of the _email.html file and do the following it does work, but this obviously is a pretty bad workaround

->setHtmlBody("<!DOCTYPE html......")

Any advice?

Thanks!

1

I think you have to set the template mode to 'SITE', to let Craft know where to look for the template:

$view = \Craft::$app->getView();         
if ($view->getTemplateMode() !== $view::TEMPLATE_MODE_SITE) {
    $view->setTemplateMode($view::TEMPLATE_MODE_SITE);
}

Craft::$app->mailer->compose('_email.html', ['body' => $emailBody])
    ->setFrom($fromMail)
    ->setTo($toMail)
    ->setSubject($subject)
    ->send();
|improve this answer|||||
1

Not exactly sure since when this is possible, but there is a way nicer way of doing this now:

<?php
$mailer = Craft::$app->getMailer();
$mailer->htmlLayout = false;
$mailer->textLayout = false;
$mailer->setViewPath('@templates/mailer');
$mailer->compose('_template_name.twig', ['user' => $user])
    ->setTo('example@example.com')
    ->setSubject('This is the subject')
    ->setTextBody('Text fallback')
    ->send();
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.