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

Enter fullscreen mode Exit fullscreen mode

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

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 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.

Top comments (5)

marvis111 profile image
Oyegbile Marvellous

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

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

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.

arielmejiadev profile image
Ariel Mejia

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

kuyajoe profile image
Kuya Joe

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

16 Libraries You Should Know as a React Developer

Being a modern React developer is not about knowing just React itself. To stay competitive, it is highly recommended to explore the whole ecosystem. This article contains some of the most useful React component libraries to speed up your developer workflow.