How to Send email with Attachement in Laravel 5.8

In this tutorial i’m going to describe how to send attachement in laravel, please follow some easy steps define below.

First let’s go to install laravel project

composer create-project laravel/laravel learning-project "5.8.*"

lets go to .env folder and put database name and connect to database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=learning-project
DB_USERNAME=root
DB_PASSWORD=

Now migrate the table

php artisan migrate

Create a Mailable class first you have to create an account in mailtrap or click this url https://mailtrap.io/ after create account you have to copy Username: XXXXXXXXX and password: XXXXXXXXXX and put in .env file see pic

Now we are ready for make mailable class for this we have to go teminal and write following

Let’s go to create controller

php artisan make:controller PDFController

Go to your PDF controller file and paste below code

<?php

namespace App\Http\Controllers;
use Log;
use PDF;
use Mail;

class PDFController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$data["email"] = "laravelamit@gmail.com";
$data["title"] = "From DevOpsSchool.com";
$data["body"] = "This is Demo";

$files = [
public_path('files/yit-brochure.pdf'),
public_path('files/laravel.png'),
];
// log::info('mail aa rha hai');
Mail::send('emails.myTestMail', $data, function($message)use($data, $files) {
$message->to($data["email"], $data["email"])
->subject($data["title"]);

foreach ($files as $file){
$message->attach($file);
}

});

dd('Mail sent successfully');
}
}

Next to create view files

resources/views/emails/myTestMail.blade.php

Go to your myTestMail.blade file and paste below code

<!DOCTYPE html>
<html>
<head>
<title>Laravel Amit</title>
</head>
<body>
<h1>{{ $title }}</h1>
<p>{{ $body }}</p>

<p>Thank you</p>
</body>
</html>

And lastone go to Routes/web.php and paste below code.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PDFController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
return view('welcome');
});

Auth::routes(['verify' => true]);

Route::get('/home', 'HomeController@index')->name('home');
Route::get('/send-email-pdf', 'PDFController@index')->name('sendemail');

Now refresh your browser and check.

Thanks …

Tagged : / / /
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x