Send mails in Laravel 10.x with Example [100% Working]


Written By - Steve Alila

This tutorial will guide you through setting up and sending emails in Laravel, covering environment setup, creating mailables, crafting email views, advanced sending techniques, and integrating third-party services. We'll also address security, troubleshooting, and FAQs.

Laravel Mail provides a simple and elegant way to send emails from your web applications, allowing you to keep your users informed and engaged. In this article, we will walk you through the process of configuring the email driver, creating a mailable, and send mails in Laravel.

 

1. Simple steps to send mails in Laravel

1.1 Setup Laravel Project

First, ensure you have Composer installed on your system. Then, create the Laravel project:

sudo mkdir -p /opt/projects
sudo chmod 777 /opt/projects
cd /opt/projects
composer create-project --prefer-dist laravel/laravel EmailerApp
cd EmailerApp

 

1.2 Generate App Password from Gmail

It is recommended to use App password from Gmail for using Gmail SMTP Server with Laravel as it adds extra layer of security.

Turn On 2-Step Verification

  1. Go to your Google Account: Sign in to your Google Account.
  2. Navigate to Security: On the left navigation panel, click on "Security".
  3. 2-Step Verification: Find the "Signing in to Google" section and click on "2-Step Verification". You might need to sign in again.
  4. Get Started: Click on "Get started" and follow the prompts to set up 2-Step Verification.

Generate App Password

After setting up 2-Step Verification, you can now create an app password:

  1. Go Back to Security Settings: If you've navigated away, return to the "Security" section of your Google Account.
  2. App Passwords: Scroll down to the "Signing in to Google" section again, and you should now see "App passwords". Click on it. You may need to sign in again.
  3. Select App: Click on "Select app" and choose "Mail" from the dropdown list.
  4. Select Device: Click on "Select device" and choose the device you're using the password with. For Laravel integration on a server, you might choose "Other (Custom name)" and type a descriptive name, like "Laravel SMTP".
  5. Generate: Click on "Generate". Google will then provide you with a 16-character app password.
  6. Copy the App Password: Make sure to copy this password and store it securely; you won’t be able to see it again. This is the password you will use in your Laravel .env file for MAIL_PASSWORD, not your Gmail account password.
Send mails in Laravel 10.x with Example [100% Working]

 

1.3 Configure Laravel Environment for SMTP

Open the .env file and configure it to use Gmail's SMTP server for sending emails. Replace placeholders with your actual Gmail account details:

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=xxxxxxxx@gmail.com
MAIL_PASSWORD=jijvixxxxxxxgmbpdz
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="xxxxxxxxx@gmail.com"
MAIL_FROM_NAME="${APP_NAME}"
NOTE:
With Gmail's SMTP server, you can either use port 465 or 587, but the choice depends on the preference of encryption protocol. The 465 port is traditionally used for SMTPS (SMTP over SSL). When using this port, the connection is SSL-encrypted from the start. This port is considered less modern than port 587 but is still used and supported. If you choose to use port 465, you should set MAIL_ENCRYPTION=ssl. The 587 port is used for submitting emails for delivery. It starts as a plaintext connection, but it upgrades to SSL/TLS encryption through the STARTTLS command if both the server and client support it. This is the recommended port for sending email as it can handle both encrypted and unencrypted connections. Use this port with MAIL_ENCRYPTION=tls

 

1.4 Configure Database (Optional)

The basic process of sending emails in Laravel, does not inherently require integration with a database. You can send emails using Laravel's Mail facade and SMTP server configuration without directly interacting with a database.

However, there are scenarios where integrating with a database might be necessary or beneficial for email functionality in your application, such as:

  1. Storing Email Logs: You might want to log sent emails' details (recipients, subjects, statuses) in the database for auditing or tracking purposes.
  2. Dynamic Recipient Lists: If you're sending emails to users stored in your database, you'll need to query their email addresses.
  3. Email Templates from Database: Storing email content or templates in the database allows for dynamic modification without deploying code changes.
  4. Scheduled Emails or Notifications: Applications that send emails based on certain events or schedules might store this configuration in a database.
  5. User Preferences: Storing user preferences for email notifications in the database to manage opt-in or opt-out settings.

Since we already have installed and setup MariaDB database so I will integrate the same with our EmailerApp:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_laravel_db
DB_USERNAME=user1
DB_PASSWORD=Passw0rd

 

1.5 Creating a Mailable Class

Generate a mailable class named SampleEmail:

php artisan make:mail SampleEmail
Send mails in Laravel 10.x with Example [100% Working]

This command creates a new class under app/Mail/SampleEmail.php. Open this file and modify the build method to specify the email subject and view:

  • The envelope() method defines the envelope of the email, such as the subject.
  • The content() method specifies which view to use for the email's body. It currently points to 'view.name', which should be replaced with the actual path to the email Blade template. Since we're creating a view for a sample email, we should replace 'view.name' with the correct view path, which is 'emails.sample' based on the file we're supposed to create at resources/views/emails/sample.blade.php.

Here is my app/Mail/SampleEmail.php:

<?php

namespace App\Mail;

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

class SampleEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Sample Email Subject',
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'emails.sample',
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [];
    }
}

 

1.6 Crafting the Email View

Create a new Blade template for the email under resources/views/emails/sample.blade.php. Add your email HTML content here:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to EmailerApp</title>
</head>
<body>
    <h1>Hello from EmailerApp!</h1>
    <p>This is a test email sent from our Laravel application.</p>
</body>
</html>

 

1.7 Sending the Email

To send an email, you can use the Mail facade in a route. Open the routes/web.php file and add a new route that sends an email using the SampleEmail mailable class:

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Mail;
use App\Mail\SampleEmail;

Route::get('/send-email', function () {
    Mail::to('recipient@example.com')->send(new SampleEmail());
    return "Email sent successfully!";
});

This code sends an email to recipient@example.com using the SampleEmail mailable class. Replace recipient@example.com with the actual recipient's email address.

 

1.8 Serve the Application

Finally, start the Laravel development server:

php artisan serve

Now, visit http://localhost:8000/send-email in your browser to send the test email.

Send mails in Laravel 10.x with Example [100% Working]

Here is the email received in my inbox:

Send mails in Laravel 10.x with Example [100% Working]

 

2. Implement Send Email Method in the Controller

For development and testing purposes, it's acceptable to place email sending logic directly in your routes/web.php file, as it provides a quick way to test email functionality without the need for a full controller or UI. However, for a more structured application or when moving to production, it's advisable to encapsulate business logic, including email sending, within controllers or event listeners, depending on the context in which the emails are sent.

Use artisan to generate a controller.

php artisan make:controller EmailController
Send mails in Laravel 10.x with Example [100% Working]

Place your email sending logic within a method of your newly created controller.

Open the generated EmailController located in app/Http/Controllers and move your email sending logic within a method of your newly created controller.

namespace App\Http\Controllers;

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

class EmailController extends Controller
{
    public function sendEmail() {
        $recipient = 'recipient@example.com'; // Change to the recipient's email address
        $data = ['name' => 'John Doe']; // Data to pass to the email view

        Mail::to($recipient)->send(new SampleEmail($data));

        return response()->json(['message' => 'Email sent successfully to ' . $recipient]);
    }
}

Next, define a route in your routes/web.php file that points to the sendEmail method of the EmailController. This creates an endpoint that you can visit in your browser or call via an HTTP client to trigger the email send action.

NOTE:
Remove the previously added Route for /send-mail and replace with below content as now we will use Controller to send mail
use App\Http\Controllers\EmailController;

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

To test the email functionality start the Laravel Development Server (if it's not already running):

php artisan serve

Open your web browser and navigate to http://localhost:8000/send-email. This will trigger the sendEmail method in your EmailController, which in turn sends the email to the specified recipient.

Send mails in Laravel 10.x with Example [100% Working]

If the email doesn't send, look at the Laravel log files in storage/logs/ for any error messages that could indicate what went wrong.

 

3. Writing Dynamic Email Views (HTML and PLAIN)

Email views in Laravel are typically Blade templates that allow you to craft both HTML and plain text content for your emails. You can use dynamic data passed to these views to personalize the emails.

 

3.1 Create or Update the HTML Email View

Navigate to resources/views/emails and create a new Blade file, e.g., welcome.blade.php. Here’s a simple example of a Blade view with dynamic content:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to Our Application</title>
</head>
<body>
    <h1>Hello, {{ $name }} ({{ $username }})!</h1>
    <p>{{ $welcomeMessage }}</p>
    <a href="{{ $startLink }}">Click here to get started</a>
</body>
</html>

For sending plain text emails, you might create a separate Blade view (e.g., welcome_text.blade.php) without HTML tags, or Laravel allows specifying a text version alongside the HTML view directly in the Mailable class.

 

3.2 Update Mailable Class

Next update your SampleEmail mailable class to accept and handle multiple pieces of dynamic data. Modify the constructor to accept an array or specific parameters, and set them as public properties so they can be accessed in the view.

Update your app/Mail/SampleEmail.php which we had created in earlier steps:

    public function __construct($name, $username, $welcomeMessage, $startLink)
    {
        $this->name = $name;
        $this->username = $username;
        $this->welcomeMessage = $welcomeMessage;
        $this->startLink = $startLink;
    }

Let's also adjust our content method to ensure the data is explicitly passed to the view:

public function content(): Content
{
    return new Content(
        view: 'emails.welcome', // Make sure this matches your actual Blade file name without the .blade.php extension
        with: [
            'name' => $this->name,
            'username' => $this->username,
            'welcomeMessage' => $this->welcomeMessage,
            'startLink' => $this->startLink
        ],
    );
}

 

3.3 Modify the controller to send dynamic data

Adjust your controller method app/Http/Controllers/EmailController.php to include the additional dynamic data when creating an instance of the SampleEmail mailable.

<?php

namespace App\Http\Controllers;

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

class EmailController extends Controller
{
public function sendEmail() {
        $recipient = 'xxxxxx@gmail.com'; // Change to the recipient's email address
        $data = [
            'name' => 'Deepak Prasad',
            'username' => 'deeepak_pd',
            'welcomeMessage' => 'Thank you for joining our platform! We’re excited to have you with us.',
            'startLink' => 'https://example.com/get-started'
        ];

        Mail::to($recipient)->send(new SampleEmail($data['name'], $data['username'], $data['welcomeMessage'], $data['startLink']));

        return response()->json(['message' => 'Email sent successfully to ' . $recipient]);
    }
}

 

3.4 Send Test Mail

Run the following Artisan commands to clear Laravel's cache, ensuring it's not serving cached content:

php artisan config:clear // Configuration Cache
php artisan cache:clear // View Cache
php artisan view:clear // Route Cache
php artisan queue:restart // If you're using queues to send emails, restart the queue workers

To access your application and trigger the email sending functionality, use Laravel's built-in development server (if it's not already running):

php artisan serve

This will trigger the sendEmail method in your EmailController, which in turn sends the email to the specified recipient.

Verify the email received:

Send mails in Laravel 10.x with Example [100% Working]

 

4. Sending Email to Multiple Recipients

To update the mail sending functionality to handle multiple recipients (To, CC, BCC) and a reply-to address, while also passing individual pieces of data to the SampleEmail constructor, you can follow this structured approach. This will ensure that your SampleEmail mailable receives the necessary data properly, and emails are sent according to your specified requirements.

Here is how you can modify app/Http/Controllers/EmailController.php

$recipient = ['user1@example.com', 'user2@example.com']; // Recipients array
$cc = 'another@example.com';
$bcc = 'hidden@example.com';
$replyToEmail = 'no-reply@example.com';
$replyToName = 'No Reply';

$data = [
    'name' => 'John Doe',
    'username' => 'john.doe',
    'welcomeMessage' => 'Welcome to our platform! We’re thrilled to have you join us.',
    'startLink' => 'https://example.com/get-started'
];

Mail::to($recipient)
    ->cc($cc)
    ->bcc($bcc)
    ->replyTo($replyToEmail, $replyToName)
    ->send(new SampleEmail($data['name'], $data['username'], $data['welcomeMessage'], $data['startLink']));

If you ever need to dynamically add recipients, CCs, or BCCs based on certain conditions, you could build up the message using conditionals before the send() method:

$email = Mail::to($recipient);

if (conditionForCC) {
    $email->cc($cc);
}

if (conditionForBCC) {
    $email->bcc($bcc);
}

$email->replyTo($replyToEmail, $replyToName)
      ->send(new SampleEmail($data['name'], $data['username'], $data['welcomeMessage'], $data['startLink']));

This approach gives you the flexibility to conditionally modify parts of the email before sending it.

 

5. Sending Email with Attachment

In the latest version of Laravel 10.x, the build function in Mailable classes has been replaced by more specific methods such as envelope, content, and attachments for configuring various aspects of the email, including sender details, view templates, and attaching files. For attachments, you can use methods like Attachment::fromPath, Attachment::fromStorage, or Attachment::fromData to attach files to your email.

I have a file available at /home/deepak/Desktop/file.txt which I will send as an attachment. To achieve this update your app/Mail/SampleEmail.php mailable class:

public function attachments(): array
{
    return [
        Attachment::fromPath('/home/deepak/Desktop/file.txt')->as('file.txt')->withMime('text/plain'),
    ];
}

This method utilizes Attachment::fromPath() to attach the file, where you can specify the file name as it would appear on the recipient mail address using as() and the file type can be declared using withMime().

The withMime method in Laravel's Mailable class allows you to specify the MIME type of the attachment you're including in your email. The supported values for MIME types correspond to the various types of files you might attach, such as application/pdf for PDF files, image/jpeg for JPEG image files, text/plain for plain text files, and so on.

My app/Http/Controllers/EmailController.php already contains the data of recipient email address from previous steps:

class EmailController extends Controller
{
public function sendEmail() {
        $recipient = 'xxxxxx@gmail.com'; // Change to the recipient's email address
        $data = [
            'name' => 'Deepak Prasad',
            'username' => 'deepak_pd',
            'welcomeMessage' => 'Thank you for joining our platform! We’re excited to have you with us.',
            'startLink' => 'https://example.com/get-started'
        ];

        Mail::to($recipient)->send(new SampleEmail($data['name'], $data['username'], $data['welcomeMessage'], $data['startLink']));

        return response()->json(['message' => 'Email sent successfully to ' . $recipient]);
    }
}

Let us now attempt to send the mail:

Send mails in Laravel 10.x with Example [100% Working]

Now verify the recipient email address:

Send mails in Laravel 10.x with Example [100% Working]

So the mail with attachment has been successfully sent and received via Laravel.

Similarly you can send multiple attachment using:

public function attachments(): array
{
    return [
        Attachment::fromPath('/home/deepak/Desktop/file1.txt')->as('file1.txt')->withMime('text/plain'),
        Attachment::fromPath('/home/deepak/Desktop/file2.pdf')->as('file2.pdf')->withMime('application/pdf'),
        // Add more files as needed
    ];
}

Now let me conclude the article, this is the list of topic we covered and learned

  • Setting up and configuring Laravel to send emails, including environment configuration.
  • Creating and customizing Mailable classes for different email contents.
  • Sending simple text emails and more complex, view-based emails.
  • Attaching files to emails using Laravel's built-in methods.
  • Testing email sending capabilities within a Laravel application.

 

You can read more at Mail - Laravel 8.x - The PHP Framework For Web Artisans

 

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment