3

Trying to send an email

Craft::$app->setViewPath('/Users/stian/dev/site.com/templates/');
Craft::$app->mailer->compose('confirmation.twig', ['orderId' => $orderId, 'customerId' => $customerId])
    ->setFrom('me@me.com')
    ->setTo('me@me.com')
    ->setSubject('hey')
    ->send();

Getting The view file does not exist: /Users/stian/dev/site.com/vendor/craftcms/cms/src/mail/confirmation.twig

Assuming I correctly understand how to render a view for sending as an email, how can I correctly point to its location?

3

For anyone struggling with this, apparently this is one way of doing it.

I struggled with this for quite some time before posting my original question, but regardless, sorry about that.

Anyway, here it is.

Craft::$app->setViewPath('/path/to/templates/');
$body = Craft::$app->getView()->renderTemplate('confirmation.twig', ['orderId' => $orderId, 'customerId' => $customerId]);
Craft::$app->mailer->compose()
    ->setFrom(['me@me.com')
    ->setTo('me@me.com')
    ->setSubject('hey')
    ->setHtmlBody($body)
    ->send();

Edit:

There's probably a better way of doing this, but if you're working in multiple environments, you can do this in general.php

'dev' => [
    'templatePath' => '/Users/stian/dev/site.com/templates/',
],
'staging' => [
    'templatePath' => '/Users/stian/dev/site.com/templates/',
],
etc

and then Craft::$app->setViewPath(Craft::$app->config->general->templatePath) in your plugin/module.

PS! Will mark as answered once I'm allowed

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.