How to Send e-mail using Laravel 5 with Example

How to Send e-mail using Laravel 5 with Example

To sending mail, Laravel provides drivers for Mandrill, SMTP, Amazon SES and PHP mail function.

Mailgun and Mandrill that are api based drivers are mostly faster and simpler rather than SMTP servers.

Guzzle HTTP library should be installed in your application if don't have installed then run this command after adding in composer.json file.

"guzzlehttp/guzzle": "~5.3|~6.0"

To use all api based driver you need to set the driver option in your config/mail.php and set credentials in config/services.php

Mailgun Driver

  1. 'mailgun' => [
  2. 'domain' => 'your-mailgun-domain',
  3. 'secret' => 'your-mailgun-key',
  4. ],
Mandrill Driver

  1. 'mandrill' => [
  2. 'secret' => 'your-mandrill-key',
  3. ],
Laravel Mail Send Example

Use Mail facade to send mail via send method. The send method contain three parameters. First parameter is your view blade file where you write your messages, second parameter is for passing array data to view and last one is closure callback that receives a message instance through which you can customize the subjects, recipients and other features of mail messages.

  1. Mail::send('email.welcome', ['name' => $name], function ($message) use($data)
  2. {
  3. $message->to($data['email'], $data['name'])->subject('Welcome to!');
  4. });

Now you can see we are passing $data in view welcome.blade.php in email directory

Access $data in view :

  1. echo $data['name']; ?>
Add Attachments

  1. Mail::send('users.file', $data, function ($message) {
  2. $message->attach($pathToFile);
  3. });

You can easily sent mail in laravel with files, you have to put your file path only in attachment method.

Send emails with activation link after successful Register

  1.     $this->validate($request, [
  2. 'name' => 'required',
  3. 'email' => 'required|email',
  4. 'password'=>'required'
  5. ]);
  6.     $user = new User;
  7.     $user->name=$request->get('name');
  8.     $user->email=$request->get('email');
  9.     $user->password=$request->get('password');
  10.    $user->verification_token = md5(uniqid('KP'));
  11.    $user->save();
  12. $activation_link = route('user.activate', ['email' => $user->email, 'verification_token' => urlencode($user->verification_token)]);
  13. Mail::send('', ['name' => $user->name, 'activation_link' => $activation_link], function ($message) use($user,$activation_link)
  14. {
  15. $message->to($user->email, $user->name)->subject('Welcome to!');
  16. });

When you have to send mail to user for reminder to activate his account then use above code to send mail after user registration

Phone: (+91) 8800417876
Noida, 201301