
How to send emails with attachments in Laravel?
In this post, we will teach you how to send emails with attachments by providing an example. In Laravels 6, 7 and 8, we have the opportunity to send attachments along with our emails. In this tutorial, as in the previous tutorials, we will use Gmail SMTP to send emails so that we can easily test the commands in localhost.
To send an email with attachments in Laravel, just follow the steps below.
- Step 1: Create the Laravel project
To create a new Laravel project, run the following command in the terminal.
composer create-project --prefer-dist laravel/laravel blog
- Step 2: Configure the env file
Open the env file and apply the following settings to send emails with the SMTP driver.
.env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_gmail@gmail.com
MAIL_PASSWORD=your_gmail_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your_gmail@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
- Step 3: Add Route
In this step, we need to create the necessary route to send the email. So open the web.php file and add the following route to it.
routes/web.php
Route::get('send-email', [MyTestMailController::class, 'index']);
- Step 4: Add Controller
In this step, we will create the MyTestMailController, which is responsible for sending the emails with attachments.
app/Http/Controllers/MyTestMailController.php
<?php
namespace App\Http\Controllers;
use Mail;
class MyTestMailController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$data["email"] = "example_email@gmail.com";
$data["title"] = "From www.maryam-hajireza.ir";
$data["body"] = "This is A Demo";
$files = [
public_path('files/path_to_file.pdf'),
public_path('files/path_to_file.png'),
];
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');
}
}
- Step 5: Create a View file
Finally, we will create the myTestMail.blade.php file to send our email with Laravel; and then we will add the following commands to it.
resources/views/emails/myTestMail.blade.php
<!DOCTYPE html>
<html>
<head>
<title>www.maryam-hajireza.ir</title>
</head>
<body>
<h1>{{ $title }}</h1>
<p>{{ $body }}</p>
<p>Thank you</p>
</body>
</html>
Finally, by running the project, you can test that the email will be sent correctly.
php artisan serve
localhost:8000/send-email