Laravel 4 uses SwiftMailer library behind the stage. They have wrapped the SwiftMailer functionality in elegant and easy to use APIs for delivering emails.
1 2 3 4 5 |
Mail::send('email.template', $data, function ($message) use ($email) { $message->subject('Message Subject'); $message->from('noreply@example.net', 'Sender Name'); $message->to($email); // Recipient address }); |
The Mail::send() API is straight forward, it takes these as argument –
# The email template to render. You can pass an array for sending both text and html emails.
# The data array which contains the values for the email template.
# A closure to configure the message. The closure is passed an instance of SwiftMailer and you can use the same set of configuration you can use with SwiftMailer.
Choosing a Mail Transport
Laravel 4 allows easy configuration of the mail transport in app/config/mail.php file. The framework has drivers for smtp, PHP’s mail() function and sendmail. If you have a local smtp server running, choose the smtp driver. Set the host to localhost and port to 25.
1 2 3 4 5 6 7 8 9 |
<?php // app/config/mail.php return array( 'driver' => 'smtp', 'host' => 'localhost', 'port' => 25, 'pretend' => false, ); |
Pretend Sending Mail
Laravel4 has a nice feature for testing emails on local machines where you probably don’t have a mail server installed and/or configured. You can switch “pretend” in the above configuration to true or use Mail::pretend(TRUE) before making a call to Mail::send(). This will not try to deliver the mail but make a log in the application log file. You can find the logs files in – “app/storage/logs” directory.
One reply on “Laravel 4: Sending Emails”
Helpful!
Thanks