
Hello Dev’s, Today in this example, I will give you a short example of how to send mail with attachment by using mailable class in laravel 8 application. So we can send email with mailable also with attach file in laravel 8 application. We can simply send a file in mail by use the attach() method in laravel 8. So you have another method in view(),attach(),attachData() etc. Here we see How to Send Email with Attachment in Laravel project.
Now we have to simple follow few steps to sending email also with attachment in laravel 8 application.
Step 1 : Mail Configuration
Now in our first step we have to add our gmail smtp configuration add our .env file and also add our configuration.
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
In next step,we have to define the make:mail command in our composer.
php artisan make:mail MyDemoMail
Now we can see a new file in our app(app/Mail/MyDemoMail.php) folder location.
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
Now in this step, we will add a new route for out testing mail so open our web route file and so add bellow route.
Route::get('my-demo-mail','TestController@myDemoMail');
Step 4 : Add Controller Method
Now, we need to add myDemoMail() in “TestController” Controller file, in this file we will also write code of mail send, so if we haven’t created TestController then need to create TestController.php file and also 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
So now we are in last step, so now we will create email template file, so first create “emails” folder in our resources folder and create myDemoMail.blade.php file and also put bellow code.
<!DOCTYPE html>
<html>
<head>
<title>Demo Mail</title>
</head>
<body>
</body>
</html>
Read Also : How to jquery set custom data attribute value?
Thanks for read. I hope it help you. For more you can follow us on facebook.