Mail Send in Laravel Example Tutorial

Mail Send in Laravel Example Tutorial

Sending Emails in Laravel

Sending emails in Laravel is a common requirement for many applications, whether for user invitations, notifications, or general communication. Laravel provides a clean and simple API for email handling using the SwiftMailer library and supports multiple mail drivers like SMTP, Mailgun, Postmark, Amazon SES, and Sendmail. This guide walks you through setting up and sending emails in a Laravel project.

Step 1: Install Laravel

First, install a new Laravel project by running the following command:

composer create-project --prefer-dist laravel/laravel Laravel_SendMail

Step 2: Set Up Database Credentials

Create a new database (e.g., custom_auth) and configure your .env file with the appropriate database credentials.

Step 3: Configure SMTP in .env

Update your .env file with SMTP settings. If you don’t have email trap details, create an account with an email service provider like Mailtrap or Gmail.

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls

Step 4: Define Routes

Add the following routes in routes/web.php for displaying the email form and sending the email:

use App\Http\Controllers\EmailController;

Route::get('/email', [EmailController::class, 'create']);
Route::post('/email', [EmailController::class, 'sendEmail'])->name('send.email');

Step 5: Create the Email Controller

Run the command to generate a new controller:

php artisan make:controller EmailController

Then, update app/Http/Controllers/EmailController.php with the following code:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class EmailController extends Controller
{
    public function create()
    {
        return view('email');
    }

    public function sendEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'subject' => 'required',
            'name' => 'required',
            'content' => 'required',
        ]);

        $data = [
            'subject' => $request->subject,
            'name' => $request->name,
            'email' => $request->email,
            'content' => $request->content
        ];

        Mail::send('email-template', $data, function ($message) use ($data) {
            $message->to($data['email'])->subject($data['subject']);
        });

        return back()->with(['message' => 'Email successfully sent!']);
    }
}

Step 6: Create the Blade View

Create an email form view in resources/views/email.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Send Email in Laravel</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Send an Email</div>
                    <div class="card-body">
                        @if(session()->has('message'))
                            <div class="alert alert-success">
                                {{ session()->get('message') }}
                            </div>
                        @endif
                        <form action="{{ route('send.email') }}" method="POST">
                            @csrf
                            <div class="form-group">
                                <label for="name">Name</label>
                                <input type="text" name="name" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email</label>
                                <input type="email" name="email" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label for="subject">Subject</label>
                                <input type="text" name="subject" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label for="content">Message</label>
                                <textarea name="content" class="form-control" rows="5" required></textarea>
                            </div>
                            <button type="submit" class="btn btn-primary">Send Email</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Step 7: Create the Email Template

Create the email template in resources/views/email-template.blade.php:

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Welcome!</div>
                <div class="card-body">
                    {{ $content }}
                </div>
            </div>
        </div>
    </div>
</div>

Conclusion

Congratulations! You have successfully implemented email sending in Laravel. Now, you can send emails with validation and templates. If you have any questions, feel free to ask!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

3 Comments

CAN FEEDBACK
  1. Unknown
    Unknown
    404 notfound when hit the post method
  2. Unknown
    Unknown
    Cannot send message without a sender address
  3. Unknown
    Unknown
    Cannot send message without a sender address
close