Sending Mail via Gmail Smtp Server in Laravel
Setup Of Gmail SMTP Server In Laravel
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
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
Now edit the details above as follows.
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
MAIL_USERNAME=ENTER_YOUR_GMAIL_ADDRESS
MAIL_PASSWORD= ENTER_YOUR_GENERATED_APP_PASSWORD
MAIL_ENCRYPTION=tls
Don't forget to run php artisan config:cache after you make changes in your .env file.
Configure your Google Account
First of all, login to your gmail account. Under My account > Sign In And Security > Sign In to Google, enable two-step verification, and then generate app password,
Send Emails from your Laravel Application
At this point, all the basic setup has been completed. We can now write some Laravel PHP codes to send an email.
To get started, create any controller of choice where the mail sending logic will be handled, then in this controller write your codes using the code snippet below as a guide.
$data = array('name'=>"sender_name", "body" => "A test mail");
Mail::send('emails.mail', $data, function($message){
$message->to('receiver_mail_address')
->subject('Laravel Test Mail');
$message->from('sender_mail_address','Test Mail');
});
In the above code, we are using our mail template as ’emails.mail’ file . hence we need to create an ‘emails’ folder and the mail.blade.php file at
resources\views\emails\mail.blade.php
Our test mail template mail.blade.php should just contains a few test codes as shown below.
Hello <strong>{{ $name }}</strong>,
<p>{{body}}</p>
simply create any route of your choice to and start sending mails from your Laravel application.