How to send contact mail in laravel
In Laravel, you can send contact mail using the Mail
facade. Here's a step-by-step guide:
Step 1: Create a new mail class
In the app/Mail
directory, create a new file called ContactMail.php
. This file will contain the logic for sending the contact mail.
Step 2: Define the mail class
In the ContactMail.php
file, define a new class that extends the Illuminate\Mail\Mailable
class:
namespace App\Mail;
use Illuminate\Mail\Mailable;
class ContactMail extends Mailable
{
public $name;
public $email;
public $message;
public function __construct($name, $email, $message)
{
$this->name = $name;
$this->email = $email;
$this->message = $message;
}
public function build()
{
return $this->markdown('emails.contact');
}
}
In this example, we're defining a ContactMail
class that has three properties: name
, email
, and message
. The __construct
method sets these properties, and the build
method returns a Mailable
instance that uses the markdown
method to render the email template.
Step 3: Create the email template
Create a new file called contact.blade.php
in the resources/views/emails
directory. This file will contain the HTML template for the email:
<h1>Contact Form Submission</h1>
<p>Name: {{ $name }}</p>
<p>Email: {{ $email }}</p>
<p>Message: {{ $message }}</p>
This template uses Blade syntax to display the name
, email
, and message
properties passed to the ContactMail
class.
Step 4: Send the mail
In your Laravel controller, create a new method that sends the contact mail:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Mail\ContactMail;
class ContactController extends Controller
{
public function sendContactMail(Request $request)
{
$name = $request->input('name');
$email = $request->input('email');
$message = $request->input('message');
$mail = new ContactMail($name, $email, $message);
Mail::to('[email protected]')->send($mail);
return redirect()->route('contact-success');
}
}
In this example, we're creating a new ContactMail
instance and passing the name
, email
, and message
properties to it. We then use the Mail
facade to send the mail to the specified email address.
Step 5: Define the mail route
In your routes/web.php
file, define a new route that calls the sendContactMail
method:
Route::post('/contact', 'ContactController@sendContactMail');
Step 6: Test the mail
Open your browser and navigate to the /contact
route. Fill out the contact form and submit it. The mail should be sent to the specified email address.
That's it! You've successfully sent a contact mail in Laravel using the Mail
facade.