How to Create and Send an Email in Laravel

Emailing doesn’t have to be a headache. With Laravel’s clean, simple email API powered by the popular Symfony Mailer component, you can quickly get started sending mail through a local or cloud-based service of your choice. The Laravel and Symfony Mailer APIs allow you to send email via SMTP, Mailgun, Postmark, Amazon SES (Simple Email Service), and Sendmail.

When you’re ready to send an email in your Laravel application, there are a few options you have. In this tutorial, we’ll look at the most straightforward way to use the Mail class in Laravel to send emails.

.env

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=yourpass
MAIL_ENCRYPTION=tls

app/Mail/MainMail.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class MainMail extends Mailable
{
    use Queueable, SerializesModels;

    public $details;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('Due for Reviewing')->view('mails.duedate');
    }
}

resources/views/mails/duedate.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Your Company: {{ $details['title'] }}</title>
</head>
<body>
    <h1>{{ $details['title'] }}</h1>
    {!! $details['body'] !!}

</body>
</html>

EmailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Auth;

use App\Equipment;
use App\Mail;

class EmailController extends Controller
{

    public function sendMail(){
        $details = [
            'title' => 'Due for Review',
            'body' => '<p>There are equipment that needs your atention: </p>'
        ];

        $details['body'] .= '<ul>';
        $dueInspections = Equipment::all();
        foreach($dueInspections as $equipment){
            $details['body'] .= '<li>'.$equipment->name.'<li>';
        }
        $details['body'] .= '</ul>';

        \Mail::to('[email protected]')->send(new \App\Mail\MainMail($details));

        dd($details);
    }


}

routes/web.php

//
Route::get('send-mail', '[email protected]')->name('sendMail');

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close