Send Email using Gmail in Laravel 10 Example

Jun 11, 2024 | Laravel 10 Laravel


Hello Dev,

In this tutorial, I'll demonstrate how to send emails using Gmail SMTP in Laravel 10. If you're wondering how to send emails via Gmail SMTP in Laravel 10, I'll provide a simple example with a solution. I'll explain the process of sending emails using Gmail SMTP in Laravel 10 in a straightforward manner.

Laravel 10 offers built-in mail configuration for sending emails, supporting various drivers such as SMTP, Mailgun, Postmark, Amazon SES, and more. In this example, we'll utilize the Google Gmail mailer driver for sending emails.

I'll provide you with step-by-step instructions on how to send emails in Laravel 10. You'll be able to create Blade file designs and incorporate dynamic information for the mail layout. Let's dive into the guide and send emails tailored to your requirements.

Step 1: Install Laravel 11

If you haven't already, create a new Laravel project:

composer create-project laravel/laravel example-app
Step 2: Make Configuration

For the initial step, configure the email sending functionality in Laravel 10 by specifying the mail driver as Gmail server along with the mail host, mail port, mail username, and mail password. Here's an example of how to do it:

.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

Ensure that you enable Google's security settings for your Gmail account. Navigate to your Google account and select "Account." Once on the "Account" page, click on "Security." Scroll to the bottom where you'll find the "Less secure app access" settings, and set it to "ON."

Send Email using Gmail in Laravel 10 Example Read Also: Laravel 10 Import Export Excel and CSV File Example Tutorial Step 3: Create Mail Class

In this step, we'll create a mail class named DemoMail for sending emails. We'll specify which view to call and pass the user object. Let's run the following command to generate the mail class:

php artisan make:mail DemoMail

now, let's update code on DemoMail.php file as bellow:

app/Mail/DemoMail.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 DemoMail extends Mailable
{
    use Queueable, SerializesModels;
  
    public $mailData;
  
    /**
     * Create a new message instance.
     */
    public function __construct($mailData)
    {
        $this->mailData = $mailData;
    }
  
    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Demo Mail',
        );
    }
  
    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'emails.demoMail',
        );
    }
  
    /**
     * Get the attachments for the message.
     *
     * @return array

     */
    public function attachments(): array
    {
        return [];
    }
}
Step 4: Create Controller

In this step, we'll create a MailController with an index() method where we'll write the code for sending mail to a given email address. Let's create the controller using the following command and then update the code accordingly:

php artisan make:controller MailController

Now, update code on MailController file.

app/Http/Controllers/MailController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Mail;
use App\Mail\DemoMail;
  
class MailController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $mailData = [
            'title' => 'Mail from ItErrorSolution.com',
            'body' => 'This is for testing email using smtp.'
        ];
         
        Mail::to('your_email@gmail.com')->send(new DemoMail($mailData));
           
        dd("Email is sent successfully.");
    }
}
Read Also: How to Upload Image Using Ajax in Laravel 10? Step 5: Create Routes

In this step, we need to create routes for handling the sending of emails. Open your "routes/web.php" file and add the following route:

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\MailController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('send-mail', [MailController::class, 'index']);
Step 6: Create Blade View

In this step, let's create a Blade view file where we'll write the email content that we want to send. For now, we'll use some dummy text. Create the following file in the "emails" folder:

resources/views/emails/demoMail.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>ItErrorsolution.com</title>
</head>
<body>
    <h1>{{ $mailData['title'] }}</h1>
    <p>{{ $mailData['body'] }}</p>
  
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
     
    <p>Thank you</p>
</body>
</html>
Step: Run the Application

Now, to run the Laravel application, please type the following command and press enter:

php artisan serve

Now, open your web browser and enter the provided URL to view the output of the application.

View Your Application
http://localhost:8000/send-mail

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#Laravel 10
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"