简体   繁体   中英

Laravel-5 how to send email from templates stored in db

How can I send email templates which are stored in a database using Laravel-5?

I am using the following code currently:

/* Queue thank you email for sending */

Mail::queue('emails.orderthankyou', $order->get()->first()->toArray(), function ($message) {
    $message->to('me@myemail.com')->subject('Thank you for your order');
});

However, currently the above template is pulled from the Resources/views directory. I need to change this as my email templates are now stored in a database, like so:

Dear {{ $first_name }},<br><br>

Thank you for your order.

How can I pull these templates from the database and render them to be sent using Mail::Queue?

Thanks in advance.

First you need to compile your template from string, if you need to use blade syntax on the string template see for example: https://github.com/TerrePorter/StringBladeCompiler

If you don't need any difficult operations, just replacing first name etc., i would go with:

// This will extract your array to variables like $first_name = 'John'
extract($order->get()->first()->toArray());
$generated = "Dear $first_name,<br><br>
            Thank you for your order.";

Now in the message

Mail::queue([], [], function ($message) use ($generated)
{
    $message->queue('me@myemail.com')
        ->subject('Thank you for your order')
        ->setBody($generated, 'text/html');
});

Notice, that Mail::queue/send first paramater is empty array, there is also setBody() method, where you first pass the generated html and then just tell it the format as text/html.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM