Sending Email with Gmail in Laravel
1 min read

Sending Email with Gmail in Laravel

There are many email clients that allow you to send email with Laravel. However, when building the MVP of my personal projects, I typically like to use Gmail to send emails for me. At some point, if the number of emails i'm sending picks up I will switch to something like sendgrid.

The first step  is updating your SMPT settings in your .env file to your Gmail settings...

MAIL_MAILER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=your_gmail_address@gmail.com
MAIL_PASSWORD=your_gmail_password
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=noreply.dotnetjobs@gmail.com

Next, you will want to create a mailable class in laravel.

php artisan make:mail SendGmail

This will generate a mailable class in Laravel that allows you to do the actual sending of the email. In the build function, add the following code.

public function build()
{
    return $this->from('no-reply@gmail.com', 'Email Subject')->view('emails.sendgmail');
}

In the above code, we are passing in the from address, email subject, and the view which will contain the contents of the email. Let's create our view now...

In the resources folder, add a subfolder of emails and within that, create a blade file called sendgmail.blade.php.

In sendgmail.blade.php, you can add your html that will make up the body of the email. For this example, we will keep it simple...

<div>
    <h1>😀 Hello World!</h1>
</div>

Almost there...

Typically, to trigger an email, it will be the result of some user action in a controller. To do this, we need to add a reference to the Laravel mail facade and the mailable class we created above. Then we can use the Mail::to function to send the email.

use Illuminate\Support\Facades\Mail;
use App\Mail\SendGmail;

.....

public function example()
{
	Mail::to('toemail@something.com')->send(new SendGmail());
}

Finally, to allow your Gmail account to send emails via an application, you have to alter your account security settings. Turn on Less Secure App Access as shown in this image.