Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Send Mail with Attachment(PDF, docs,image) in Laravel

How to Send Mail with Attachment(PDF, docs,image) in Laravel 8 /9 ?

Aman Jain, May 10, 2022May 10, 2022

Attachment with mail is very important feature of mail by which we can attach any document with our email , for example in some scenarios we want to send the invoice to user mail or some guideline to user after registration. So in this article we will learn to use send mail with attachment(PDF, docs,image) in laravel. Email is very common operation of any website like sending an email to users after registration, sending invoice, PDF, DOC, Send newsletters to users and many more. Laravel provides multiple drivers or services to send mail from different different providers.

attach() Method :

Laravel mailer class uses attach() method to add the attachment in mail. attach() method accepts first parameter as full file path and second as options like filename and mime type as below

return $this->view('emails.test')
                ->attach('full/path/to/file', [
                    'as' => 'name.pdf',
                    'mime' => 'application/pdf',
                ]);

If you want to attach a uploaded file then

return $this->view('emails.test')
                ->attach(request()->file("document")->getRealPath(), [
                   'as' => request()->file("document")->getClientOriginalName(),
                    'mime' => request()->file("document")->getClientMimeType(),
                ]);

//or

return $this->view('emails.test')
                ->attach($this->document->getRealPath(), [
                   'as' => $this->document->getClientOriginalName(),
                    'mime' => $this->document->getClientMimeType(),
                ]);

Attach File from Disk:

If you want to attach a file from storage folder which is already stored in storage folder then you can use attachFromStorage method

public function build()
{
   return $this->view('emails.test')
               ->attachFromStorage('/path/to/file',[
                    'as' => 'name.pdf',
                    'mime' => 'application/pdf',
                ]);
}

Attach from other disk like s3 :

May be sometimes we need to attach from other storage rather then default file storage so we can use attachFromStorageDisk

public function build()
{
   return $this->view('emails.test')
               ->attachFromStorageDisk("s3",'/path/to/file',[
                    'as' => 'name.pdf',
                    'mime' => 'application/pdf',
                ]);
}

Attach Raw Data (PDF in memory or String of Byte):

Sometimes you make some file in memory only and not save in storage so in that case you can use attachData method

public function build()
{
   return $this->view('emails.test')
               ->attachData($this->file,name.pdf,[
                    'mime' => 'application/pdf',
                ]);
}

Laravel gives wide range of options to send emails. We can queue an email for send on specific time using the queue drivers.

Following are the supported methods of Laravel mail

  1. Amazon SES
  2. MailGun
  3. Sendmail
  4. SparkPost
  5. SMTP

Laravel Mailing supports blade views based templating system so you can easily configure the mail body layout same as other pages.

It also gives a easy to implements mail with attachment feature so let’s start with example

Step 1: Create a laravel project

First step is to create the Laravel 8 project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations

composer create-project laravel/laravel example-app

Step 2 : Configure the mail

SMTP

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=username
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=fromaddress
MAIL_FROM_NAME="${APP_NAME}"

 If the website is secure ssl then change ‘encryption’ => ‘tls’ to ’encryption’ => ‘ssl’ and ‘port’ => 465

Step 3 : Generate Mailable Class

In laravel 8 or 9 every mail is implements mailable class thus first we need to create a mail class as follow

php artisan make:mail TestMail

This will create a class in following location App\Mail\TestMail.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

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()
    {
        return $this->view('test');
    }
}

Update the code as below

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class TestMail extends Mailable
{
    use Queueable, SerializesModels;
    private $user;
    private $data;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($user,$data)
    {
        $this->user=$user;
        $this->data=$data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from('info@readerstacks.com')
               ->subject('Mail from readerstacks.com')
                ->attach($this->data['document']->getRealPath(),
                [
                    'as' => $this->data['document']->getClientOriginalName(),
                    'mime' => $this->data['document']->getClientMimeType(),
                ]);

               ->view('emails.test',["user"=>$this->user,"title"=>"Register"]);
    }
}

Step 4 : Create View for Mail

Create a simple view for mail body in resources/views/emails/test.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Readerstacks.com</title>
</head>
<body>
    <h1>Hello {{ $user['name'] }}, download the attachement</h1>
    
    <p>{{ $user['body'] }}</p>
    <p>Thanks to visit us.</p>
    
</body>
</html>

Step 5 : Create Route and Send Mail

Now, create a route and call Mail methods in inline function as below

<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;


Route::get('/send-mail',function(Request $request){
 $user = [
        'name' => 'Readerstacks',
        'body' => 'This is simple mail from Readerstacks'
    ];
 $data = [
        'document' => $request->file("document"),
         
    ];
   
    \Mail::to('receiver_email@domain.com')->send(new \App\Mail\TestMail($user,$data ));
   
});

Also Read : How to Send Mail in Laravel Through Gmail SMTP ?

Related

Php Laravel Laravel 9 Attachmentemaillaravelphpsendmailsmtp

Post navigation

Previous post
Next post

Related Posts

Php How to Restore Soft Deleted Records in Laravel 9

How to Restore Soft Deleted Records in Laravel 9 ?

June 16, 2022June 15, 2022

In this article we will learn to restore soft deleted records in Laravel. In our recent article How to fetch Soft Deleted Records in Laravel 9 ? we learnt to fetch the records from database which is soft deleted and sometimes we want to restore records that are soft deleted…

Read More
Php How to change data type of column in laravel migration

How to change data type of column in laravel migration ?

February 20, 2022November 5, 2023

In this blog post we will learn to change data type of column in laravel migration. Laravel covers most of the migration features like add, delete, indexing etc. but to modify the table like renaming column, change data type column to existing table laravel uses a separate package doctrine/dbal. In…

Read More
Php How to Change Date Format in Blade View File in Laravel

How to Change Date Format in Blade View File in Laravel ?

September 8, 2022March 16, 2024

Laravel default shows the date in the way its stored in database bu sometimes we want to change date format in blade view file in laravel according to our requirements. It can be multiple possibilities and requirement from client or product manager to change the date format so in this…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version