Email sending

This guide explains how to send emails in a Laravel application using the built-in Mail functionality.

Configuration

First, configure your email settings in the .env file. For example, if you are using Gmail SMTP:

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your app password
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

Creating a Mailable Class

Next, create a Mailable class which defines the email content:

php artisan make:mail ExampleMail

This will generate a new file in app/Mail/ExampleMail.php.

ExampleMail.php

namespace App\Mail;

  public function envelope(): Envelope
  {
    return new Envelope
        from: new Address('your_email@gmail.com', 'Your Name')
        subject: 'Test Mail'
  }
}
  public function content(): Content
  {
    return new Content(
        view: 'welcome' );
  }
}

Creating the Email View

Create a Blade file at resources/views/example.blade.php:

<h1>Hello from Laravel!</h1>
<p>This is a test email.</p>

Sending the Email

Finally, you can send the email from a controller:

use App\Mail\ExampleMail;
use Illuminate\Support\Facades\Mail;

public function sendEmail()
{
  Mail::to('recipient@example.com')->send(new ExampleMail());
  return 'Email sent successfully!';
}

With this setup, you can easily send emails in Laravel!