Laravel 11 for Beginners: Sending Emails

Arlind Musliu Portrait
Arlind Musliu

January 19, 2024 · 3 min read · 374 views

Laravel Sending Email Subscriptions

2024 UPDATE - LARAVEL 11

We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, we wanted to ensure that our readers have access to the most up-to-date information and examples.

Email Communication with Laravel

Whether you're sending out newsletters, post notifications, or password reset links, email communication is a staple of any application. Laravel simplifies the process of sending emails with its clean, expressive API and support for a variety of mail services.

Understanding Email Configuration in Laravel

Before you start sending emails, you'll need to configure your mail service in Laravel. The framework supports several drivers out of the box, including SMTP, Mailgun, Postmark, and Amazon SES. You can set up your mail configuration in the config/mail.php file and your .env file with details like your mail server, port, username, and password.

Here's an example .env configuration for an SMTP server using Mailtrap:

// Other options

MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_mailtrap_username
MAIL_PASSWORD=your_mailtrap_password

// Other options

Creating Mailables

In Laravel, each type of email sent by your application is represented as a "Mailable" class. You can generate a new mailable using the command:

php artisan make:mail NewPostPublished

This command creates a new mailable class in the app/Mail directory. Within this class, you define the content and configuration of your email. Here's a simple example:

<?php

namespace App\Mail;

use App\Models\Post;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class NewPostPublished extends Mailable
{
    use Queueable, SerializesModels;

    public $post;

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

    public function build()
    {
        return $this->view('emails.posts.published')
                    ->subject('A New Post Has Been Published')
                    ->with([
                        'title' => $this->post->title,
                        'content' => $this->post->content,
                    ]);
    }
}

In the build method, you specify the view that will be used as the email's content and pass any necessary data to the view.

Sending Emails

To send an email, you use the Mail facade with the send method, passing in the mailable instance:

<?php

namespace App\Http\Controllers;

use App\Jobs\SendNewPostNotification;
use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
		// Other stuff

        // Store the blog post...
        $post = Post::create($request->all());

		// Send the email
		Mail::to('[email protected]')->send(new NewPostPublished($post));

        // Other stuff
    }
}

This code is placed in a part of your application where the email should be sent, such as after a new post is created.

Laravel Queues Jobs Illustration

Queueing Emails

Sending emails synchronously during a request can slow down your application. Laravel allows you to queue emails for background sending, improving response time for your users:

<?php

namespace App\Http\Controllers;

use App\Jobs\SendNewPostNotification;
use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {
		// Other stuff

        // Store the blog post...
        $post = Post::create($request->all());

		// Send the email
		Mail::to('[email protected]')->queue(new NewPostPublished($post));
        
		// Other stuff
    }
}

To process queued emails, make sure you have set up your queue driver and are running a queue worker as we explained in a previous article.

Laravel best PHP framework

Conclusion

Sending emails in Laravel is a straightforward process that can greatly enhance the functionality of your application. Whether it's for user registration, post notifications, or marketing campaigns, Laravel's built-in email capabilities provide you with the tools to communicate effectively with your readers.

Upcoming Articles in the Series

  1. Laravel for Beginners: Localization and Languages

  2. Laravel for Beginners: Query Performance Issues and Debugbar

  3. Laravel 11 for Beginners: API Resources

This article is part of our series Laravel 11 for Beginners: A Step-by-Step Guide to Learn the Concepts.


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!