Hi coders. In this tutorial, i’ll show you how to send email with attachment using Mailable class in laravel . You can simply send file in mail by using the attach() method.
In this example, i will simply add files as attachment with sending email. Let’s dive in.
1- Mail Configuration
First thing to do is to configure your SMTP in .env file.
1 2 3 4 5 6 7 8 9 | MAIL_DRIVER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_USERNAME=yourgoogle@gmail.com MAIL_PASSWORD=yourpassword MAIL_ENCRYPTION=tls MAIL_FROM_ADDRESS=yourgoogle@gmail.com |
2- Create Mailable Class
Next, you have to execute the make:mail command in your composer.
1 2 3 | php artisan make:mail TestMail |
Now you can find new file in “app/Mail/TestMail.php” folder.
Make sure you have to add “example.pdf” file public folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class TestMail extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { $mail = $this->view('emails.testMail'); $mail = $mail->attach(public_path('pdf/example.pdf'), [ 'as' => 'example.pdf', // optional 'mime' => 'application/pdf', // optional ]); // you can add other attachment if you want return $mail } } |
3-Â Add Route
Now we need to create route to send mail. Open your “routes/web.php” file and add following route.
1 2 3 | Route::get('test-mail','TestMailController@index'); |
4- Add Controller
To add controller execute the following command.
1 2 3 | php artisan make:controller TestMailController |
Edit controller file in app/Http/Controllers/TestMailController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use Mail; use App\Mail\TestMail; class TestMailController extends Controller { public function index() { $myEmail = 'receiver@gmail.com'; Mail::to($myEmail)->send(new TestMail()); dd("Email sent successfully"); } |
5- Add View File
Last, we need to create email template view file in “resources/views/emails/testMail.blade.php” and put the following code :
1 2 3 4 5 6 7 8 9 10 11 | <!DOCTYPE html> <html> <head> <title>Test Mail Template</title> </head> <body> <h1> Email With Attachment </h1> </body> </html> |
Now you can run and check example.
I hope it can help you :).
Leave a Reply