How to Send Email with Attachment in Laravel 12

Hi there! If you’re building a web application with Laravel 12 and need to send emails with attachments, you’re in the right place. Sending emails is a common feature in web apps, whether it’s for sending invoices, reports, or user notifications.

Laravel makes this super easy with its built-in Mail system. In this article, I’ll share a beginner-friendly, step-by-step guide to help you send emails with attachments like PDFs or images in Laravel 12.

Step-by-Step Guide to Send Email with Attachment in Laravel 12

How to Send Email with Attachment in Laravel 12

Sending an email with an attachment in Laravel 12 is straightforward if you follow these steps. I’ll explain each one clearly so you can follow along, even if you’re new to Laravel.

Step 1: Set Up a Laravel 12 Project

First, I need to create a new Laravel 12 project. If you already have a project, skip this step. Open your terminal and run:

composer create-project --prefer-dist laravel/laravel laravel-email-example
cd laravel-email-example

This command sets up a fresh Laravel 12 application. Make sure you have Composer installed and a web server like XAMPP or Laravel’s built-in server ready.

Step 2: Configure Email Settings in .env

Next, I’ll configure the email settings in the env file to tell Laravel how to send emails. For this tutorial, I’ll use Mailtrap for testing, but you can use Gmail, Sendgrid, or any SMTP service.

Open the env file in your project root and update it with the following:

MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_mailtrap_username
MAIL_PASSWORD=your_mailtrap_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="[email protected]"
MAIL_FROM_NAME="Your App Name"

You can get the Mailtrap credentials by signing up at Mailtrap and adding a sending domain. If you’re using Gmail, you’ll need an App Password and set MAIL_HOST=smtp.gmail.com with MAIL_PORT=587.

Step 3: Create a Mailable Class

Laravel uses Mailable classes to structure emails. Let’s create one to handle our email with an attachment. Run this Artisan command in your terminal:

php artisan make:mail AttachmentEmail

This creates a file at app/Mail/AttachmentEmail.php. Open it and update it to include attachment logic:

<?php
namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Mail\Mailables\Attachment;

class AttachmentEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $mailData;

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

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: $this->mailData['title'],
        );
    }

    public function content(): Content
    {
        return new Content(
            view: 'emails.attachment_email',
        );
    }

    public function attachments(): array
    {
        return [
            Attachment::fromPath(public_path('attachments/sample.pdf'))
                ->as('Sample Document.pdf')
                ->withMime('application/pdf'),
        ];
    }
}

This code sets up the email’s subject, content view, and attaches a PDF file from the public/attachments directory. Make sure you have a file named sample.pdf in that directory.

Step 4: Create an Email Template

Now, I’ll create a Blade template for the email’s content. Create a file named attachment_email.blade.php in resources/views/emails/ and add:

<!DOCTYPE html>
<html>
<head>
    <title>{{ $mailData['title'] }}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }
        .container { max-width: 600px; margin: 0 auto; background: #f9f9f9; padding: 20px; }
        h1 { color: #333; }
        p { color: #555; }
    </style>
</head>
<body>
    <div class="container">
        <h1>{{ $mailData['title'] }}</h1>
        <p>Hello, {{ $mailData['name'] }}!</p>
        <p>{{ $mailData['body'] }}</p>
        <p>Please find the attached document.</p>
        <p>Thank you!</p>
    </div>
</body>
</html>

This template defines a simple HTML email with a title, greeting, and message, styled for better readability.

Step 5: Create a Controller

I’ll create a controller to handle sending the email. Run:

php artisan make:controller EmailController

Open app/Http/Controllers/EmailController.php and add:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\AttachmentEmail;

class EmailController extends Controller
{
    public function sendEmail()
    {
        $mailData = [
            'title' => 'Test Email with Attachment',
            'name' => 'John Doe',
            'body' => 'This is a test email with a PDF attachment sent from Laravel 12.'
        ];

        Mail::to('[email protected]')->send(new AttachmentEmail($mailData));

        return response()->json(['success' => 'Email sent successfully.']);
    }
}

This controller sends an email to a specified recipient with the attachment.

Step 6: Set Up a Route

To trigger the email, I’ll define a route. Open routes/web.php and add:

use App\Http\Controllers\EmailController;

Route::get('/send-email', [EmailController::class, 'sendEmail']);

Step 7: Test the Email

Finally, I’ll test the setup. Start the Laravel development server:

php artisan serve

Visit http://localhost:8000/send-email in your browser. If everything is set up correctly, you’ll receive an email with the PDF attachment in your Mailtrap inbox (or your chosen email service).

Conclusion

And that’s it! Sending emails with attachments in Laravel 12 is easier than it sounds. By following these steps, I’ve shown you how to configure Laravel’s email system, create a Mailable class, design a simple email template, and attach files like PDFs. This feature is super useful for sending invoices, reports, or any files to users. With Laravel’s clean API and Mailtrap for testing, you can ensure your emails work perfectly before going live. Try experimenting with different file types or queueing emails for better performance!

Frequently Asked Questions(FAQs)

Q: Can I send multiple attachments in Laravel 12?
A: Yes! In the attachments() method of your Mailable class, add more Attachment::fromPath() entries for each file you want to attach.

Q: What email services can I use with Laravel 12?
A: Laravel supports SMTP, Mailgun, Postmark, Amazon SES, and more. You can configure them in the .env file.

Q: How do I test emails without sending them to real users?
A: Use Mailtrap or similar services to test emails in a sandbox environment. Update your .env file with the service’s credentials.

Q: Can I send emails asynchronously in Laravel 12?
A: Yes, use Laravel’s queue system. Implement the ShouldQueue interface in your Mailable class and use Mail::queue() instead of Mail::send().

Q: What file types can I attach to emails?
A: You can attach any file type (PDF, images, CSV, etc.) as long as you specify the correct MIME type in the attachments() method.


You might also like :

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS