How to Send Email with Attachment in Laravel 6?

10-Apr-2023

.

Admin

How to Send Email with Attachment in Laravel 6?

hii guys,

In this example,I will give you how to send mail with attachment using mailable class in laravel 6.you can send email with mailable with attach file in laravel 6.you can simply send file in mail use the attach() method in laravel 6.you can antoher method in view(),attach(),attachData() etc.

You have to simple follow few steps to sending email with attachment in laravel 6.

Step 1 : Mail Configuration


In first step you have to add your gmail smtp configuration add your .env file and add your configration.

MAIL_DRIVER=smtp

MAIL_HOST=smtp.gmail.com

MAIL_PORT=587

MAIL_USERNAME=atmaninfotech@gmail.com

MAIL_PASSWORD=mypassword

MAIL_ENCRYPTION=tls

Step 2 : Create Mailable Class

Next step,you have to define the make:mail command in your composer.

php artisan make:mail MyDemoMail

Now you can see new file in your app(app/Mail/MyDemoMail.php) folder.

Make sure you have to put "sample.pdf" file in pdf folder in public folder.

app/Mail/MyDemoMail.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;

use Illuminate\Mail\Mailable;

use Illuminate\Queue\SerializesModels;

use Illuminate\Contracts\Queue\ShouldQueue;

class MyTestMail extends Mailable

{

use Queueable, SerializesModels;

/**

* Create a new message instance.

*

* @return void

*/

public function __construct()

{

}

/**

* Build the message.

*

* @return $this

*/

public function build()

{

return $this->view('emails.myDemoMail')

->attach(public_path('pdf/sample.pdf'), [

'as' => 'sample.pdf',

'mime' => 'application/pdf',

]);

}

}

Step 3 : Add Route

In this step, we will add new route for out testing mail so open your web route file and add bellow route.

Route::get('my-demo-mail','TestController@myDemoMail');

Step 4 : Add Controller Method

Now, we will add myDemoMail() in "TestController" Controller file, in this file we will write code of mail send, so if you haven't created TestController then create TestController.php file and put bellow code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use Mail;

use App\Mail\MyDemoMail;

class TestController extends Controller

{

/**

* Send My Demo Mail Example

*

* @return void

*/

public function myDemoMail()

{

$myEmail = 'aatmaninfotech@gmail.com';

Mail::to($myEmail)->send(new MyDemoMail());

dd("Mail Send Successfully");

}

}

Step 5 : Add View File

In last step, we will create email template file, so first create "emails" folder in your resources folder and create myDemoMail.blade.php file and put bellow code.

<!DOCTYPE html>

<html>

<head>

<title>Demo Mail</title>

</head>

<body>

</body>

</html>

It will help you....

#Laravel

#Laravel 6