Basic mail in laravel

In Laravel, sending an email is a straightforward process. Here's a basic example of how to send an email using the Mail facade:

Step 1: Create a new email class

In the app/Mail directory, create a new PHP file (e.g., WelcomeEmail.php). This file will contain the email content and logic.

Step 2: Define the email class

In the WelcomeEmail.php file, define a new class that extends Illuminate\Mail\Mailable:

namespace App\Mail;

use Illuminate\Mail\Mailable;

class WelcomeEmail extends Mailable
{
    public $name;
    public $email;

    public function __construct($name, $email)
    {
        $this->name = $name;
        $this->email = $email;
    }

    public function build()
    {
        return $this->markdown('emails.welcome');
    }
}

In this example, we're defining a WelcomeEmail class that has two properties: name and email. We're also defining a constructor that sets these properties. The build method returns a Mailable instance that will be used to render the email template.

Step 3: Create an email template

In the resources/views/emails directory, create a new Blade template file (e.g., welcome.blade.php). This file will contain the email content.

Step 4: Send the email

In your controller or service, use the Mail facade to send the email:

use Illuminate\Support\Facades\Mail;

//...

Mail::to($user->email)->send(new WelcomeEmail($user->name, $user->email));

In this example, we're using the Mail facade to send an email to the user's email address. We're passing an instance of the WelcomeEmail class to the send method, which will render the email template and send the email.

Step 5: Configure the email settings

In your config/mail.php file, configure the email settings:

'mail' => [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.gmail.com'),
    'port' => env('MAIL_PORT', 587),
    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
        'name' => env('MAIL_FROM_NAME', 'Your Name'),
    ],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
],

Make sure to set the MAIL_DRIVER, MAIL_HOST, MAIL_PORT, MAIL_FROM_ADDRESS, MAIL_FROM_NAME, MAIL_USERNAME, and MAIL_PASSWORD environment variables accordingly.

That's it! With these basic steps, you should be able to send an email using Laravel.