Email functionality is an essential aspect of web applications, and Laravel provides convenient methods to simplify the process. Let's explore two commonly used methods, raw
and plain
, that facilitate sending plain text emails in Laravel.
The raw Method for Sending Plain Text Emails
The raw
method in Laravel's Mail facade allows you to send plain text emails by passing the desired text as an argument. The following example demonstrates its usage:
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Mail;
Mail::raw('Hello world', function (Message $message) {
$message->to('you@gmail.com')->from('me@gmail.com');
});
In this case, Hello world
is the plain text content of the email. The to
method specifies the recipient's email address, while the from
method determines the sender's email address.
The plain Method for Sending Templated Emails
To send templated emails with dynamic content, we can use Laravel's plain
method. It accepts three arguments: the view
, data
, and a callback
function. Which might look like this:
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Mail;
Mail::plain(
view: 'welcome',
data: [
'name' => 'Charles'
],
callback: function (Message $message) {
$message->to('example@gmail.com')->from('me@gmail.com');
}
);
Here, the first parameter - welcome
corresponds to a Blade template file that defines the email's structure. The second argument, data
, allows you to pass any necessary variable parameters to the email template. In the provided example, the character
variable is passed as a parameter to the plain
method.
// welcome.blade.php
<h1>Welcome to the list, {{ $name }}!</h1>
In the above Blade template, the value of the name
variable is inserted into the email's content. In this case, it would generate the string:
"Welcome to the list, Charles!".
By utilizing the plain
method, you can send templated emails with dynamic content, making your email communication more personalized and engaging.
Conclusion
While trivial and simple examples, Laravel can be a little overwhelming to new users. I found this the most accessible way to look at it when I started out. Whether you need to send a simple message or include dynamic content, these methods provide flexibility and convenience, and can be built on in the future.
No comments yet…