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:
- Login into your Google account
- Click on the security tab
- Enable 2FA
- Click on App passwords Select Mail in the app select dropdown. For device, select others and give it the name you want.
- Click on generate 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
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');
});
});
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)
the code
+ $ip
in the Mail command should be. $ip
Thanks a lot for this article. It really helped me!
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
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.
It should be as you said, is something to highlight and thanks it sounds like an amazing solution