How to send email in laravel?

by herminia_bruen , in category: PHP Frameworks , 5 months ago

How to send email in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , a month ago

@herminia_bruen 

Sending email in Laravel is a straightforward process. Here's how you can send an email in Laravel:

  1. First, make sure you have configured your email settings in the .env file of your Laravel application. You need to set up your mail driver, host, port, username, and password.
  2. Next, create a new Mailable class by running the following command in your terminal:
1
php artisan make:mail MyTestMail


This will create a new file in the app/Mail directory with the name MyTestMail.php.

  1. Open the newly created Mailable class and customize the build method to define the email content and settings. You can set the subject, view, and other email attributes in this method.
  2. Once your Mailable class is set up, you can send an email using the Mail facade. Here's an example of how you can send an email in a controller or anywhere else in your application:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use AppMailMyTestMail;
use IlluminateSupportFacadesMail;

public function sendEmail()
{
    $details = [
        'name' => 'John Doe',
        'message' => 'This is a test email from Laravel.'
    ];

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

    return "Email sent successfully";
}


Replace the email address in the to method with the recipient's email address.

  1. Finally, you can test the email sending functionality by using the php artisan serve command and accessing the endpoint where the sendEmail method is called.


That's it! You have successfully sent an email in Laravel. Remember to check your email client to see if the email has been delivered.