DEV Community

Cover image for Sending Email in Laravel App Using Gmail Account
Akeem Amusat
Akeem Amusat

Posted on • Updated on

Sending Email in Laravel App Using Gmail Account

Laravel framework made sending email very easy for developers using the Mailable class. I will be using an existing Laravel 8 application. You can also follow the tutorial using other Laravel versions (6 or 7). Follow the steps below to configure your Laravel app for sending mail.

Step one: generate app password on Google account

App password is required by your application to access Gmail account via SMTP or other protocol. To create the app password:

  1. Login into your Google account
  2. Click on the security tab image
  3. Enable 2FA
  4. Click on App passwords image Select Mail in the app select dropdown. For device, select others and give it the name you want.
  5. Click on generate image Copy the generated app password.

Step two: update your application .env

MAIL_DRIVER=smtp
MAIL_FROM_ADDRESS=user@gmail.com
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=user@gmail.com
MAIL_PASSWORD=App Password
MAIL_ENCRYPTION=tls
Enter fullscreen mode Exit fullscreen mode

Step three: send the email using the Laravel built-in Mail facade.

<?php
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Mail;

Route::get('/sendmail', function (Request $request) {
    $ip = $request->ip();
    Mail::raw('Hi user, a new login into your account from the IP Address: '+$ip, function ($message) {
        $message->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'));
        $message->to('user@domain.com', 'User Name');
    });
});
Enter fullscreen mode Exit fullscreen mode

You can read more about sending mail, adding attachments, sending mail using Laravel blade templates: visit the Laravel Mail documentation for more details.
Follow me for more of my articles, you can leave comments, suggestions, and reactions.

Oldest comments (5)

Collapse
 
arielmejiadev profile image
Ariel Mejia

Just take in mind that it wont be useful if your app is going to send a huge amount of emails, gmail will block the app ip

Collapse
 
aoamusat profile image
Akeem Amusat

Thanks for your response. I have used this solution for Gmail Workspace Account and I have never experience the issue of IP blocking before. Maybe the IP blocking thing is peculiar to personal Gmail accounts.

Collapse
 
arielmejiadev profile image
Ariel Mejia

It should be as you said, is something to highlight and thanks it sounds like an amazing solution

Collapse
 
kuyajoe profile image
Kuya Joe

the code + $ip in the Mail command should be . $ip

Collapse
 
marvis111 profile image
Oyegbile Marvellous

Thanks a lot for this article. It really helped me!