Laravel: Sending email with attachments

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Sending emails with attachments is a common requirement for modern web applications. Laravel, being a robust PHP framework, provides an elegant solution to send emails with attachments seamlessly using its built-in mail functionality. In this tutorial, we will guide you through the process of sending emails with different types of attachments in Laravel, starting with basic examples and progressing to more advanced use cases.

Setting up Email Configuration

Before sending emails, you must configure your mail driver in Laravel. Edit your .env file with the correct mail settings:

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

After editing the .env file, clear your config cache with php artisan config:cache.

Basic Email with Attachment

To send a basic email with an attachment, you can use the Mail facade with the mailable class. Here’s an example of how to do it:

use Illuminate\Support\Facades\Mail;
use App\Mail\InvoiceMail;

Mail::to('[email protected]')->send(new InvoiceMail());

The InvoiceMail class should extend Illuminate\Mail\Mailable and include the attachment in the build method:

use Illuminate\Mail\Mailable;

class InvoiceMail extends Mailable
{
    public function build()
    {
        return $this->subject('Your Invoice')->view('emails.invoice')->attach('/path/to/invoice.pdf');
    }
}

You should now have a view file named invoice.blade.php in your resources/views/emails directory with the content of the email.

The recipient should receive the email with the PDF invoice attached.

Multiple Attachments

Attaching multiple files to an email is as simple as chaining multiple attach methods:

public function build()
{
    return $this->subject('Your Documents')->view('emails.documents')
        ->attach('/path/to/first/document.pdf')
        ->attach('/path/to/second/document.pdf');
}

Each file you want to attach can be added with its own attach call. The emails sent out will include both of the documents you’ve attached.

Attaching From Raw Data

You can also attach files using raw data by using the attachData method:

public function build()
{
    $content = '...'; // The raw data of your file
    return $this->subject('Your Dynamic Document')->view('emails.dynamic')->attachData($content, 'dynamic-doc.pdf', [
            'mime' => 'application/pdf',
        ]);
}

In this case, dynamic-doc.pdf being the filename that will appear on the email.

Advanced Usage

For more advanced email attachment scenarios, such as conditionally adding attachments or manipulating large files, you can exercise finer control over the attachment process.

public function build()
{
    $email = $this->subject('Customized Documents')->view('emails.customized');
    if ($condition) {
        $email->attach('/path/to/conditional/document.pdf', [
            'as' => 'custom-name.pdf',
            'mime' => 'application/pdf',
        ]);
    }
    return $email;
}

In the snippet above, an attachment is conditionally added to the email with a custom filename and specific MIME type.

Sending Emails with attachments using Job Queue

Laravel’s queue system can offload the email sending process to a job, improving the response time of your application for the end-user. Here is an example of queueing an email with attachments:

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;

class SendInvoiceEmailJob implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public $invoice;

    public function __construct($invoice)
    {
        $this->invoice = $invoice;
    }

    public function handle()
    {
        Mail::to('[email protected]')->send(new InvoiceMail($this->invoice));
    }
}

To dispatch this job, use the following:

dispatch(new SendInvoiceEmailJob($invoice));

Your email will be added to the queue and sent in the background.

Conclusion

Sending emails with attachments in Laravel is a straightforward task that can be customized to fit your application needs. Whether you are sending simple notifications or complex automated email responses with multiple attachments, Laravel provides a clean and maintainable approach. Remember to always test your email functionality in a safe environment before going live to avoid accidental data leaks.