How to send html format through email in laravel?

Member

by dana , in category: PHP Frameworks , a month ago

How to send html format through email in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , a month ago

@dana 

To send HTML-format emails in Laravel, you can use the with method along with the view method to send an email using a blade template. Here's an example:

1
2
3
4
5
6
7
8
9
use IlluminateSupportFacadesMail;
use AppMailMyEmail;

public function sendEmail()
{
    $data = ['name' => 'John Doe'];
    
    Mail::to('[email protected]')->send(new MyEmail($data));
}


Next, you need to create a Mailable class in Laravel using the following command:

1
php artisan make:mail MyEmail


This will create a new Mailable class in the app/Mail directory that you can customize to include your HTML email content. Here's an example of what the MyEmail class may look like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
use IlluminateBusQueueable;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;
use IlluminateContractsQueueShouldQueue;

class MyEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function build()
    {
        return $this->view('emails.myemail')
                    ->subject('Test HTML Email');
    }
}


In the build method, you can set the view (blade template) that you want to use for the email. Make sure to create a blade template named myemail.blade.php in the resources/views/emails directory to contain your HTML email content.


You can then use HTML markup within the myemail.blade.php file to format your email content as needed.


Finally, you can send the email with the desired HTML content by calling the sendEmail method in your controller.


Note that you may also need to configure your mail settings in the .env file to use a mail driver that supports HTML content, such as SMTP.