DEV Community

Emmanuel Larbi
Emmanuel Larbi

Posted on

Sending mails in Laravel 9

logo

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 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
Enter fullscreen mode Exit fullscreen mode

Create a new laravel project

composer create-project laravel/laravel laravelmail
Enter fullscreen mode Exit fullscreen mode

Make a mailable class.

php artisan make:mail SimpleMail
Enter fullscreen mode Exit fullscreen mode

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');
        }
    }
Enter fullscreen mode Exit fullscreen mode

Create a controller for mailable class

php artisan make:controller SimpleMailController
Enter fullscreen mode Exit fullscreen mode

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';
        }
    }
Enter fullscreen mode Exit fullscreen mode

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>

Enter fullscreen mode Exit fullscreen mode

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']);

Enter fullscreen mode Exit fullscreen mode

Preview

Now run the server

    php artisan serve
Enter fullscreen mode Exit fullscreen mode

home

Then goto http://127.0.0.1:8000/sendmail

sent

In mail inbox (Mailtrap)

mail

Top comments (1)

Collapse
 
timoye profile image
Timothy Soladoye

Nice article