How to Send Emails in Laravel 12

How to Send Emails in Laravel 12

How to Send Emails in Laravel 12

Table of Contents

    Sending emails is a crucial part of modern web applications, whether it's for user registration, notifications, or marketing purposes. Laravel 12 simplifies email handling with its built-in mail functionality. This guide will walk you through the process of setting up email sending in Laravel 12 using Gmail SMTP, helping you send emails efficiently and securely.

    By the end of this tutorial, you will have a fully functional Laravel email system ready to integrate into your projects.

    Step 1: Setting Up Laravel 12 Project

    Start by creating a new Laravel 12 project: create one with Composer:

                                        
                                            composer create-project --prefer-dist laravel/laravel laravel12-Send-Email                                     
                                        
                                    

    Navigate to the app directory by running the following command in your terminal

                                        
                                            cd laravel12-Send-Email                               
                                        
                                    

    Step 2: Gmail SMTP Configuration

    To enable email sending, configure Gmail SMTP in the .env file:

                                        
                                            MAIL_MAILER=smtp
                                            MAIL_HOST=smtp.gmail.com
                                            MAIL_PORT=587
                                            MAIL_USERNAME=your@gmail.com
                                            MAIL_PASSWORD=your-app-password  # Use App Password, not Gmail password
                                            MAIL_ENCRYPTION=tls
                                            MAIL_FROM_ADDRESS=your@gmail.com
                                            MAIL_FROM_NAME="Your App Name"                                        
                                        
                                    

    If you face authentication issues, enable "Less Secure Apps" in your Google account or generate an App Password.

    Step 3: Create a Mailable Class

    Laravel's Mailable classes provide a structured way to send emails. To create a new Mailable class, run the following command:

                                        
                                            php artisan make:mail SubscriberEmail
                                        
                                    

    Open the generated file app\Mail\SubscriberEmail.php and update it as follows:

                                        
                                            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 SubscriberEmail extends Mailable
                                            {
                                                use Queueable, SerializesModels;
                                            
                                                public $param_data = [];
                                                /**
                                                 * Create a new message instance.
                                                 */
                                                public function __construct($param_data)
                                                {
                                                    $this->param_data = $param_data;
                                                }
                                            
                                                /**
                                                 * Get the message envelope.
                                                 */
                                                public function envelope(): Envelope
                                                {
                                                    return new Envelope(
                                                        subject: 'Subscriber Email',
                                                    );
                                                }
                                            
                                                /**
                                                 * Get the message content definition.
                                                 */
                                                public function content(): Content
                                                {
                                                    return new Content(
                                                        view: 'emails.subscribe-email',
                                                    );
                                                }
                                            
                                                /**
                                                 * Get the attachments for the message.
                                                 *
                                                 * @return array
                                                 */
                                                public function attachments(): array
                                                {
                                                    return [];
                                                }
                                            }                                        
                                        
                                    

    Customize your Mailable by setting the subject, choosing a Blade template for HTML design, and adding dynamic data like title variable.

    Once you've set up your Mailable class, sending an email in Laravel is simple. Laravel provides the Mail facade, which allows you to send emails effortlessly.

    Example: Sending a Subscribe Email

    Use the following code to send an email using the SubscriberEmail Mailable class:

                                        
                                            use Illuminate\Support\Facades\Mail;
                                            use App\Mail\SubscriberEmail;
    
                                            Mail::to('recipient_gmail@example.com')->send(new SubscriberEmail());
                                        
                                    

    How It Works:

    • Specify the Recipient: The to('recipient_gmail@example.com') method defines the email recipient.
    • Use the Mailable Class: The new SubscriberEmail() creates an instance of the email template.
    • Send the Email: The send() method dispatches the email immediately.

    Step 4: Design Email Template

    Create a Blade template for the email:

                                        
                                            php artisan make:view emails.subscribe-email                           
                                        
                                    

    Customize resources/views/emails/subscribe-email.blade.php with your design.

                                    
                                            <!doctype html>
                                            <html lang="en">
                                            <head>
                                                 <meta charset="UTF-8">
                                                 <title>Welcome to Our Platform</title>
                                                 <style>
                                                    /* Inline styles for simplicity, consider using CSS classes for larger templates */
                                                    body {
                                                        font-family: Arial, sans-serif;
                                                        margin: 0;
                                                        padding: 0;
                                                    }
                                                    .container {
                                                        max-width: 600px;
                                                        margin: 0 auto;
                                                        padding: 20px;
                                                        background-color: #f1f1f1;
                                                    }
                                                    .message {
                                                        padding: 20px;
                                                        background-color: #ffffff;
                                                    }
                                                    </style>
                                                    </head>
                                                    <body>
                                                 
                                                <div class="container">
                                                    <div class="message">
                                                        <h1>{{$param_data['title']}}</h1>
                                                        <h1>Thank you for subscribing to our newsletter</h1>
                                                    </div>
                                                </div>
                                                
                                            </body>
                                            </html> 
                                    
                                    

    You can use the data from the Mailable class directly in your email view, making it easy to display dynamic content.

    Step 5: Send Email via Controller

    Generate a controller using the following Artisan command. This controller will handle the logic for send mail

                                        
                                            php artisan make:controller SubscriberController
                                        
                                    

    Open the generated file App\Http\Controllers\SubscriberController.php and update it as follows:

                                        
                                            namespace App\Http\Controllers;
                                            
                                            use Illuminate\Http\Request;
                                            use Illuminate\Support\Facades\Mail;
                                            use App\Mail\SubscriberEmail;
                                            class SubscriberController extends Controller
                                            {
                                                public function subscribe(Request $request)
                                                {
                                                    try {   
                                            
                                                        $to_email = "recipient_gmail@gmail.com";
                                            
                                                        $mailData = [           
                                                            'title' => 'Welcome to tipinfotrove.com'
                                                        ];           
                                                       
                                                        Mail::to($to_email)->send(new SubscriberEmail($mailData));
                                                
                                                        return response()->json(['status' => true,'message' => 'Thank you for subscribing!'],200);
                                                        
                                                    } catch (\Exception $e) {
                                                        return response('An error occurred: ' . "Something goes wrong!!", 500);
                                                    }         
                                                }
                                            }                                        
                                        
                                    

    Step 6: Define Routes and Run the Application

    1. Add Route

      Define the route in routes/web.php

                                                  
                                                      use App\Http\Controllers\SubscriberController;
      
                                                      Route::post('/send-subscribe-mail', [SubscriberController::class, 'subscribe'])->name('subscribe');            
                                              
    2. Run the Project

      Start the development server:

                                                  
                                                      php artisan serve                                         
                                                  
                                              
    3. Preview the Application

      Open your web browser and navigate to the following URL to view the Send Email Response:

      Preview:

      Sending subscribe mail request

      Received subsccried email

    Read Also: Laravel 12 REST API Tutorial: Build a CRUD API Step-by-Step

    Conclusion

    Congratulations! You've successfully set up email sending in Laravel 12 using Gmail SMTP. You've learned how to configure SMTP, create a Mailable class, design an email template, and send emails via a controller.

    Now, you can integrate email functionality into your Laravel projects for user notifications, password resets, and more.

    Get the complete source code on GitHub: Click here to download Code

    Did this solution work for you? Drop a like or comment below!

    Satish Parmar

    Satish Parmar

    Experienced Full-Stack Web Developer

    I'm a passionate full-stack developer and blogger from India, dedicated to sharing web development tips and solutions. As the creator of TipInfoTrove.com, my goal is to help developers and tech enthusiasts solve real-world challenges with expertise in PHP, Laravel, JavaScript, Vue, React, and more. Through detailed guides and practical insights, I strive to empower others to excel in their projects and stay ahead in the ever-evolving world of technology.

    0 Comments

    Post Comment

    Your email address will not be published. Required fields are marked *