To use this site please enable javascript on your browser! Bryce Andy | Send an Email in Laravel 5.7 Using Gmail SMTP

Send an Email in Laravel 5.7 Using Gmail SMTP


Bryce on Oct 12, 2018

Gmail

Sending emails is a crucial event in any web application. Using the Laravel framework, one of the most popular tools in web-development based in PHP, allows us to send an email through many drivers such as SMTP, Mailgun, SparkPostAmazon SES, PHP's mail function and sendmail as of the current framework's release of Laravel 5.7.

 

We are going to explore the nitty-gritty on how Gmail uses the SMTP driver of Laravel's SwiftMailer API to send emails easily in our applications. So, why even send an email in the first place? Use-cases in web applications might include, but not limited to:

Enough with the chit-chat, let us get into the good stuff...

Kermit typing

Create a Mailable

Assuming you have a Laravel app already installed on your particular environment, head over your (CLI) command-line interface and type the following;

php artisan make:mail GmailExample

This artisan command enables the creation of a Mailable class which is the base of an email. Let's name it GmailExample as seen above. If we open the Mail directory in app/Mail, there we can see our newly created mailable GmailExample.php looking like this;

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class GmailExample extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('view.name');
    }
}

For this example, we are going to send a very simple email that carries its variables explicitly and uses a markdown instead of plain text or basic html. Markdowns are brilliant for quick styling which reduces the pain off of a developer. So modify the build function so that it has a sender, subject, receives a markdown and a few variables. 

public function build()
    {
        return $this->from('mail@example.com', 'Bryce Andy')
            ->subject('Our Example')
            ->markdown('mails.exmpl')
            ->with([
                'name' => 'Joe Doe',
                'link' => 'http://www.bryceandy.com'
            ]);
    }

 

Customize Your Markdown

SO, now we can create our markdown. Inside the directory resources/views, create a file called 'mails' and inside it a blade template name it 'exmpl.blade.php'. This is because we specified the location of the mailable as mails.exmplMarkdowns use components to determine the structure of its content. Modify your exmpl blade template like the following ;

@component('mail::message')

Hi <b>{{$name}}</b>,

Congrats for delivering this email!

It looks neat, no?<br />

@component('mail::button', ['url' => $link])

Take Me Back <br/>

@endcomponent

Regards,<br />
DevBlog.

@endcomponent

 To customize the CSS for this markdown, first we need to publish the Laravel vendor files that have default CSS corresponding to the markdown. Publishing them makes it easy for us to modify the in-built styles of the components since we can not edit the vendor file that is shipped with the framework. Now inside your CLI type the following artisan command

php artisan vendor:publish --tag=laravel-mail

Head over to the directory resources/views/vendor/mail/html/themes, and there you will find a default.css file. As you can see from our markdown template, we have components such as message & button, others are panel, footer, header etc.

This default sheet can be modified as you can see the styles for every component and other HTML elements of the markdown. You are not tied to using this default theme as you can make use of any css file you want by just specifying i at the end of the config/mail.php file. 

 

Set Up a Route

In order to send this email we need to specify a route like the following in the routes/web.php file

<?php

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

Route::get('/send-mail', function () {

    Mail::to('write your email here')->send(new GmailExample()); 

    return view('/');

});

Using the Laravel's Mail facade we can now send this email if we visit the yoursite/send-mail or for local environment localhost/send-mail, depending on what your site name is and upon success it will return you to the home page, but...we haven't set any configurations for Gmail yet, so wait up.

Chill

Allow 2-factor Authentication & Create an App Password

This is the most important step in order to make this Gmail service work perfectly for your emailing. You might perfect every step in the workarounds to send emails with Gmail but if you miss any step of this section then you must be running into a couple of SwiftMailer exceptions and other errors on authentication with Gmail.

 

Onto your Gmail account go to My Account > Sign In & Security > Sign In and you can see a section where you click to enable 2-Factor Authentication. After that is done, click on the following section App Passwords and create an app password.

 

Mail Configuration

After creating your app password, back to your Laravel project and inside config/mail.php, make sure your configs match this

<?php

return [


    'driver' => env('MAIL_DRIVER', 'smtp'),


    'host' => env('MAIL_HOST', 'smtp.gmail.com'),


    'port' => env('MAIL_PORT', 587),


    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],


    'encryption' => env('MAIL_ENCRYPTION', 'tls'),


    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    'sendmail' => '/usr/sbin/sendmail -bs',

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];

Only a few configuration values are changed and that's because our .env file is supposed to match this below on the MAIL fields

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=yourGmailEmail
MAIL_PASSWORD=yourAppPasswordGeneratedFromGmail
MAIL_ENCRYPTION=tls

NOTE: For production, storing your config credentials like an app password and committing it into a repository is not advisable as you are exposing your Gmail credentials to the public. Incase you are in production, it's still not bad news because hosting your Laravel app on for example Heroku you can manage your configuration values and save them there.

 

That's how I do it most of the time in production, set the env configurations on Heroku and barely change the .env file. After all that use this artisan command to clear and cache your configurations

php artisan config:cache

 Before sending the email we should make sure we change the app name in config/app.php because the footer of the email will display the app name. Now we can hit the yoursite/send-mail route to send our email, and voila

voila

Conclusion

Creating an email could be tedious if you miss the vital points of the process. You may be successful with sending emails this way, but a service like Gmail is not always reliable.

For example, recently after setting this up correctly and sending lots of emails, I realised Gmail has a tendancy of blocking emails so you have to reactivate to resend again. I suggest for longevity, we can use dedicated email delivery services like this I posted here.

 

Find a domain starting at $0.88

powered by Namecheap

 

 

Any remarks may be thrown right at me down the comments below, and for any help or consultation on web applications contact me through hello@bryceandy.com . 


Tags




  • user 0 1 year ago

    Hey, thank you very much! I made it through all of the steps, but get the following error message: There is no existing directory at "...jay1/storage/logs" and its not buildable: Permission denied
    • user Bryce  1 year ago

      Was this issue solved ?



  • user 0 1 year ago

    Hey, thank you very much, great article!
    • user Bryce  1 year ago

      You are welcome



Bryce
Bryce is a web developer based in Dar. Apart from writing code, you can find him in the gym, writing informative articles or playing football.


Copyright © Bryce Andy 2018