Laravel mail: pass string instead of view

I want to send a confirmation e-mail using laravel. The laravel Mail::send() function only seems to accept a path to a file on the system. The problem is that my mailtemplates are stored in the database and not in a file on the system.

How can I pass plain content to the email?

Example:

$content = "Hi,welcome user!";

Mail::send($content,$data,function(){});

Solution 1:

update: In Laravel 5 you can use raw instead:

Mail::raw('Hi, welcome user!', function ($message) {
  $message->to(..)
    ->subject(..);
});

This is how you do it:

Mail::send([], [], function ($message) {
  $message->to(..)
    ->subject(..)
    // here comes what you want
    ->setBody('Hi, welcome user!'); // assuming text/plain
    // or:
    ->setBody('<h1>Hi, welcome user!</h1>', 'text/html'); // for HTML rich messages
});

Solution 2:

For Html emails

Mail::send(array(), array(), function ($message) use ($html) {
  $message->to(..)
    ->subject(..)
    ->from(..)
    ->setBody($html, 'text/html');
});

Solution 3:

The Mailer class passes a string to addContent which via various other methods calls views->make(). As a result passing a string of content directly won't work as it'll try and load a view by that name.

What you'll need to do is create a view which simply echos $content

// mail-template.php
<?php echo $content; ?>

And then insert your string into that view at runtime.

$content = "Hi,welcome user!";

$data = [
    'content' => $content
];

Mail::send('mail-template', $data, function() { });

Solution 4:

It is not directly related to the question, but for the ones that search for setting the plain text version of your email while keeping the custom HTML version, you can use this example :

Mail::raw([], function($message) {
    $message->from('[email protected]', 'Company name');
    $message->to('[email protected]');
    $message->subject('5% off all our website');
    $message->setBody( '<html><h1>5% off its awesome</h1><p>Go get it now !</p></html>', 'text/html' );
    $message->addPart("5% off its awesome\n\nGo get it now!", 'text/plain');
});

If you would ask "but why not set first argument as plain text ?", I made a test and it only takes the html part, ignoring the raw part.

If you need to use additional variable, the anonymous function will need you to use use() statement as following :

Mail::raw([], function($message) use($html, $plain, $to, $subject, $formEmail, $formName){
    $message->from($fromEmail, $fromName);
    $message->to($to);
    $message->subject($subject);
    $message->setBody($html, 'text/html' ); // dont miss the '<html></html>' or your spam score will increase !
    $message->addPart($plain, 'text/plain');
});

Hope it helps you folks.

Solution 5:

try

public function build()
{
    $message = 'Hi,welcome user!'
    return $this->html($message)->subject($message);
}