Send mail in Laravel 5.x

Tram Ho

1. Introduction

As you know, for most applications, sending mail is a function that seems indispensable in the dozens of functions that the application must have. Today I will write a tutorial on how to send mail with Laravel 5.x.

Laravel uses a feature-rich and completely free SwiftMailer library for sending mail. In the past, sending mail to the library and config was quite complicated, but with this library in Laravel, we can easily send mail without too much trouble. SwiftMailer provides popular drivers such as SMTP, Mailgun, SpartPost, … will help us deploy the mailing feature much simpler and easier.

2. Install the package

All API drivers require the Guzzle HTTP library, which you can install through the Composer package manager with the following command:

3. Config file mail environment variables in the .env file

I explain a bit offline

The method to send mail is SMTP, host of gmail is , port is 587, MAIL_USERNAME is your gmail, and MAIL_PASSWORD is your password. Here we need to note a few of the following:

If your gmail has 2-layer security turned on, it will not be possible to login to send mail with the gmail password as usual you still use to login, now you need to create an application password for gmail and get that password fill in the MAILPASSWORD key. Instructions on how to create an app password for gmail can be found here

Or if you do not like using the .env file, we can configure in config/mail.php

Now we can leave the mail config key in the .env file because if it is in the .env file, the value will be taken from the .env file only, next we find the keys corresponding to the key in the .env file and correct it to your liking, otherwise it will use the default values.

4. Test the mailing function

Here we will test the sending function in the simplest way, not to mention creating the mailable class, we will only test the sending function via processing in a controller.

Create a controller file

Copy the following code into the newly created MailController.php file

Create a template file to test the view of the mail

resources / views / mail.blade.php Copy the code below into the newly created template file

Create route

app / Http / routers.php Copy the following code into the route file

Then visit the following url to check basic email

And the output screen will look like this

Next, visit the url http://localhost:8000/sendhtmlemail to check email with html

Output screen of html

And finally visit the following url http://localhost:8000/sendattachmentemail to check email with attachments. We will see the following screen:

5. Finish

So basically we have the configuration and conditions for sending mail in the most basic way. This article is also a pretty basic guide and there are definitely shortcomings that you can contribute and ignore. 😅

Reference source:

Share the news now

Source : Viblo