As you all know laravel come with the default mailtrap.io SMTP, Are you trying for Gmail SMTP server for sending email in Laravel? Sometimes PHP default mail() functions also not able to send emails due to some server settings or configurations. In this case, we can use SMTP server for sending emails. In this article, we discuss how to send email using Gmail SMTP server in Laravel.
One more benefit of using SMTP server is, you can send email from your local server also. By this way, it will helpful for us to test the email functionality on the local server itself. And there is log in laravel, you can take help of that too for email notification so you get your email HTML in your log file instead of your inbox.
Laravel use config/mail.php file for storing details related to sending emails. This file contains settings like MAIL_DRIVER, MAIL_HOST, MAIL_PORT, etc. For sending email we need to provide this information.
To add these setting, we don’t need to edit config/mail.php. We should store these details in the .env file.
Open your .env file which is located in your root directory and you will find below code related to email settings.
MAIL_DRIVER=smtp
Edit above with the given below
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=YOUR_GMAIL_USERNAME
MAIL_PASSWORD=ENTER_YOUR_GMAIL_PASSWORD
MAIL_ENCRYPTION=tls
Here, we set driver as smtp, host for gmail as smtp.gmail.com, smtp port for gmail as 465 and encryption method to ssl. Make sure you have replaced your Gmail username and password.
As we are using Gmail SMTP, we need to change some settings on our Google account. Login to your Google account and click on My Account. Once you are on My Account page then click on Security. Scroll down to the bottom and you will find ‘Less secure app access’ settings. Set it to ON.
At this stage, we are completed with all basic setup. Now, we need to write a Laravel code which will send an email.
Your code will something like as below.
Route::get('/sendemail',function(){
$to_name = 'TO_NAME';
$to_email = 'TO_EMAIL_ADDRESS';
$data = array('name'=>"Jhon Doe", "body" => "Hello Jhon Doe, Hope you fine!");
Mail::send('Your_view_file_name', $data, function($message) use ($to_name, $to_email) {
$message->to($to_email, $to_name)
->subject('Ecodeblog Test Email');
$message->from('FROM_EMAIL_ADDRESS','Ecodeblog - A Tech blog');
});
});
In the above code, i have used the view file emails.mail. It means i have folder and files in resources->views->emails->mail.blade.php path.
Here, I have mail.blade.php file that will contains code look like as below.
Hi <strong>{{ $name }}</strong>,
<p>{{ $body }}</p>
That’s it! Laravel in the background automatically use Gmail SMTP server and send an email.