Chapter 13- Sending Email using SMTP
Hello Artisan's, welcome to the 13th chapter of being an Artisanary. In this chapter we'll show how to send mail using SMTP. For sending mail we'll use mailtrap. So if you already complete the previous chapters/sections, then you're good to go, if not my recommendation would be please complete the previous chapters. Because we'll use the same old repository that we use in chapter 4.
Note: Tested on Laravel 10.0
So, we'll not gonna use a different route or different action for sending mail. As we already have a list of user, then we'll notify the user when he/she deleted by admin. So let's modify the destroy() function of UserController.php like below
public function destroy($id): \Illuminate\Http\RedirectResponse
{
DB::beginTransaction();
try {
$user = $this->userRepository->find($id);
Mail::send('email.account_delete', [
'data' => $user
], function ($message) use ($user) {
$message ->to($user->email);
$message ->subject('Account Deleted');
});
$this->userRepository->destroy($id);
DB::commit();
return back()->with('success', 'User deleted successfully');
} catch (\Exception $e) {
DB::rollBack();
return back()->with('error', $e->getMessage());
}
}
Now we need to setup our view file. So, create view file called email/account_delete.blade.php, and put the below source code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Account Delete</h1>
<p>Hi {{ $data->name }},</p>
<p>We are sorry to see you go. Your account has been deleted.</p>
<p>Best regards,</p>
<p>Admin</p>
</body>
</html>
First of all we need the below credential that we need to must be fill up in .env file.
MAIL_MAILER=
MAIL_HOST=
MAIL_PORT=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=
MAIL_FROM_ADDRESS="[email protected]"
MAIL_FROM_NAME="${APP_NAME}"
And all this information you'll get it from the mailtrap My inbox page. You can see the below screenshot for dthe details view
Get this information and put into the .env file. And your setup is done.
And finally we're ready with our setup. It's time to check our output. Now if you delete any user, If everything goes well you'll find a below output.
N.B. This method should be worked in any SMTP available thers. Either it'll be Google SMTP or SendinBlue.
So, We saw the sending email using SMTP. And yes keep up to date with the Github repository. That's it for today. See you in my next chapter. Happy coding ๐.