Sending mails in Laravel 9
Tags: laravel, tutorial, mail
Published: 2022-09-02 11:17:27


![logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d2wfsf3j8xr66xdl59ir.jpg)

## Laravel Mail

Laravel has made mail sending simple, clean, fast, and reliable  by providing simple email API component using drivers like SMTP, Mailgun, Postmark, etc. The emails can be sent through a cloud or local service. Let's setup a simple mail locally using laravel.

## Steps

### Get a mail service provider. We will use [Mailtrap](https://mailtrap.io/) as our test provider.
#### Create an account and copy and paste the configuration for Laravel in `.env` file.
>You can skip this if you already have a mail provider.

    MAIL_MAILER=smtp
    MAIL_HOST=smtp.mailtrap.io
    MAIL_PORT=2525
    MAIL_USERNAME=//username
    MAIL_PASSWORD=//password
    MAIL_ENCRYPTION=tls
### Create a new laravel project

    composer create-project laravel/laravel laravelmail

### Make a mailable class.
    php artisan make:mail SimpleMail

#### The mail class can be found at `/app/Mail/SimpleMail.php`. Copy this block of code and replace it with yours. 
```
<?php
    namespace App\Mail;
    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Mail\Mailable;
    use Illuminate\Queue\SerializesModels;

    class SimpleMail extends Mailable
    {
        use Queueable, SerializesModels;

        /**
        * Create a new message instance.
        *
        * @return void
        */
        public function __construct()
        {
            //
        }

        /**
        * Build the message.
        *
        * @return $this
        */
         public function build()
        {
            return $this->from(config('MAIL_USERNAME'))
            ->view('mail.simplemail');
        }
    }
```
### Create a controller for mailable class
    php artisan make:controller SimpleMailController
#### The created controller can be found at `app/Http/Controllers/SimpleMailController.php`, replace this code with yours. 

```
<?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use Mail;
    class SimpleMailController extends Controller
    {
        public function index() {
            $passingDataToView = 'Simple Mail Send In Laravel!';
            $data["email"] = 'test@mail.com';
            $data["title"] = "Mail Testing";

            Mail::send('mail.simplemail', ['passingDataToView'=> $passingDataToView], function ($message) use ($data){
                $message->to($data["email"],'John Doe');
                $message->subject($data["title"]);
            });;

            return 'Mail Sent';
        }
    }
```

### Create a view for the mailable class.
#### Goto the resource folder and create a folder named `mail`, then create a blade file named `simplemail` inside the `mail` folder. Your file path should look like this `resources\mail\simplemail.blade.php`. Then paste this code inside the `simplemail.blade.php` file.
```
 <div style="background-color: white;border: 2px solid #0f0870;box-shadow: 20px -13px 1px 1px #0f0870;
        width: fit-content;padding: 1rem 1rem;font-family: system-ui;">
            <h4 style="text-align: center; font-size: large;"> {{ $passingDataToView }}</h4>
            <h4 style="font-size: medium"> This is a custom mail</h4>
            <p style="font-size: medium">
                Laravel provides flexiblity for you to design your mail format to your liking
            </p>
            <p style="font-size: medium">
                Enjoy and explore the world of infinite possibilities 
            </p>
            <small>Thanks for checking this tutorial out.</small>
            <p style="display:flex;justify-content: center;align-items: center;">
                <a style="padding: 1rem;background-color: #0f0870;
                    width: max-content;color: white;text-decoration: none;" 
                    href="https://medium.com/@manu_tech">
                    Custom Button
                </a>
            </p>
    </div>

```
### Create a route to send mail.
```
<?php

    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\SimpleMailController;
    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */

    Route::get('/', function () {
        return view('welcome');
    });

    Route::get('sendmail', [SimpleMailController::class, 'index']);

```
## Preview
### Now run the server
        php artisan serve

![home](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b01zwisirctx4pwyl8at.png)
#### Then goto `http://127.0.0.1:8000/sendmail`

![sent](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ee6k6vnao1o6lwa5sr2.png)

### In mail inbox (Mailtrap)

![mail](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/obo8h7se4sz72n9mr5re.png)