Sending Email with Laravel 5

Sending emails to users is the Essential act for any web application. Several uses of mailing like confirmation, acknowledgement and inform to subscribe users about the new post.

This is a small snippet of Mail::send() method. There are 3 parameters provided by Mail::send().

<?php
Mail::send('emails.welcome', $data, function($message)
{
  //
});
  • The first argument is a view file welcome.blade.php which contain formatted page sends by the web application to the users.
  • The second argument is the data which we’d like to pass email view file. Passed data can be variable or array.
  • The third argument is a closure with the instance of a $message. This argument specifies some information to users in an email like who we are, to send you an email and subject messages.    

So in this section of the tutorial I will show you, How to store and send mail to newly subscribed users.
Suppose that, We have a subscription form which have name and email address fields.
Firstly, Getting the values of both fields and store them into the users table. After that, We will send mail to every individual user who will fill subscription form. 

<?php
if ($validator->passes()) {
$user = new User;
$user->name = Input::get('name');
    $user->email = Input::get('email');
    $user->save();
 
    Mail::send('users.mails.welcome', $name = Input::get('name')), function($message){
        $message->to(Input::get('email')->subject('Welcome to the Laravel 5 App!');
    });
 
    return Redirect::to('users')->with('message', 'Thanks for Subscription!');
} else {
    return Redirect::to('users/register')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
}

Inside the send() method the first argument is a welcome.blade.php view page, second argument we passing a $name variable to view file and third parameter is $message, Where passing user email address and subject message.

We accomplish all processing to send mail but here is our welcome.blade.php file :

<h1>Hello, {{ $name }}!</h1>
 
<p>We'd like to personally welcome you to the Laravel Application. Thank you for registering!</p>

 

Something to say? Tell us in comment section.