Laravel mail: pass string instead of view
For Html emails
Mail::send(array(), array(), function ($message) use ($html) {
$message->to(..)
->subject(..)
->from(..)
->setBody($html, 'text/html');
});
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() { });
update on 7/20/2022: For more current versions of Laravel, the setBody()
method in the Mail::send()
example below has been replaced with the text()
or html()
methods.
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
});
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.