Implementing mailing function in Laravel project

Tram Ho

Preface

At the beginning of the spring of the new year, I had an idea of ​​sending a happy new year mail to my acquaintances, and at the same time I realized that my Laravel project did not mention the extremely important function. this. So I decided to write about a function that makes sure every website needs.

  • When registering an account on a website, the first thing is you will have to go to the email to activate the account.
  • When customers place an order on your website, you need to send a confirmation mail to the customer.
  • When websites have promotions, advertising by mail is an extremely simple and useful method.

So you have seen the practicality of the function to send mail yet? And in this article I will go into two main content, which is:

  • How can you build a mailing function?
  • How to test if the sending function is working correctly?

Now let’s get down to business!

content

Built in mailing function

  • As a first step , to send email, you will need to install Guzzle HTTP library via composer:
  • Then, we’ll create a command to call the mailing function with the command:

    We will get the appConsoleCommandsSendMail with the following structure:
  • Step 2 , we use the php artisan make:mail NewYearMail to create the NewYearMail class:
  • Step 3 , we will create a blade for the content of the email:

Test your mailing function with Mailtrap

  • Firstly, let’s briefly talk about how mailtrap works:
    • Normally, to check the content of mail, you must send an email to see it. But in order to test the function, you will have to repair it and test it, resulting in spam mailbox.
    • And Mailtrap solves that problem by YES creating mail, YES sending but will BE STAY midway and stored in the mailtrap mailbox, no longer reach the recipient. So you will avoid spamming the mailbox or using bogus mail and still be able to check the content of outgoing emails.
  • After you register your mailtrap account successfully, access to the mailbox will appear configuration information as shown below. And in the Integration section, you choose the corresponding language / framework. As I am here, I will choose Laravel

Then copy the configuration information below (do 1 of 2 things) into:

  • Configuration in .env:
  • OR in config / mail.php

Installing mailtrap is as simple as that, now let’s test it to see if it works!

Now we will run the command php artisan email:newyear 1 to send email to the user with id = 1 and here is the result I obtained:

summary

After this article, hope you have been able to build up the function of sending email according to your website product. If there are any difficulties during the implementation, you can comment below or post a question on viblo for everyone to support!

Thank you for watching and please support me in the next article!

References

Share the news now

Source : Viblo