Send mail in Laravel using MailHog

Tram Ho

Hello everyone, when developing a web application, mailing tasks are used very often, so today, I will show you how to send mail in Laravel using  MailHog . In actual work, there will be a lot of tools to use for sending mail such as  Mailtrap, MailHog,… but I suggest you to use MailHog, because it only sends under local machine so it will avoid some security issues later (in the past I used to use Mailtrap because it was quite convenient and was told by the guys in the company )

Steps to take

Install Laravel App

In this article, I will use Laravel 8 to perform, first run the familiar command to install the Laravel application.

Create routes and interfaces

Before creating a route, you need to create a controller for sending mail by command

After creating the controller, we add a mail router and make a simple interface for sending mail, including 2 inputs, the recipient’s email address, and the content we want to send.

Make email delivery

1. Install MailHog

To send mail, you need to install MailHog, you can go to its docs to see it https://github.com/mailhog/MailHog. Here I will install using docker with Docker file as below.

Do a docker image build and run on port 1025 and 8025

2. Configure MailHog in .env

3. Make a Mailable

Execute the command below to create a mailable, it will be saved in folder app/Mail

In function build you can set email like fromviewwithattach, … In the code below, I send email with subject is “Send mail contact!” use markdown in file resources/views/Mails/send_mail.blade.php and receive data through __construct and assign to variable $this->data(Remember to let the public file view be able to receive it)

In the view file, I will create a simple information to display the email content. Out $data is $this->data in the above mailable file.

4. Send mail in controller

After user enters email and content and press submit, we will redirect to function sendMail in MailController, Here, remember to add validate required for email and content Please

Result

Summary

Sending mail needs to be careful, it may be wrong to send mail to end users, to users of the whole system, … so it must be re-tested when performing. In addition, sending mail will take a long time for the application to load, so you should use  Queues  for sending mail. Thank you everyone for following my post.

Share the news now