Laravel's Mail
class extends the popular Swift Mailer package, which makes sending e-mails a breeze. The e-mail templates are loaded in the same way as views, which means you can use the Blade syntax and inject data into your templates:
To inject some data into a template located inside
resources/views/email/view.blade.php
, we use the following function:Mail::send('email.view', $data, function($message) {});
To send both an HTML and a plain text version, we use the following function:
Mail::send(array('html.view', 'text.view'), $data, $callback);
To delay the e-mail by 5 minutes (this requires a queue), we use the following function:
Mail::later(5, 'email.view', $data, function($message) {});
Inside the $callback
closure that receives the message object, we can call the following methods to alter the message that is to be sent:
$message->subject('Welcome to the Jungle');
$message->from('[email protected]', 'Mr. Example');
$message->to('[email protected]', 'Mr. Example');
Some of the less common methods include:
$message->sender('[email protected]', 'Mr. Example');
$message->returnPath('[email protected]');
$message->cc('[email protected]', 'Mr. Example');
$message->bcc('[email protected]', 'Mr. Example');
$message->replyTo('[email protected]', 'Mr. Example');
$message->priority(2);
To attach or embed files, you can use the following methods:
$message->attach('path/to/attachment.txt');
$message->embed('path/to/attachment.jpg');
If you already have the data in memory, and you do not want to create additional files, you can use either the attachData
or the embedData
method as follows:
$message->attachData($data, 'attachment.txt');
$message->embedData($data, 'attachment.jpg');
Embedding is generally done with image files, and you can use either the embed
or the embedData
method directly inside the body of a message, as shown in the following code snippet:
<p>Product Screenshot:</p> <p>{!! $message->embed('screenshot.jpg') !!}</p>