In this tutorial we will learn how to send mail using PHPMailer in Laravel.
How to send mail using PHPMailer in Laravel
PHPMailer is a popular PHP library that simplifies sending emails via SMTP or other mail transport methods.
Here's a step-by-step guide on how to send emails using PHPMailer in Laravel:
Step 1 - Install Laravel Project:
If you haven't already, create a Laravel project or use an existing one.
composer create-project --prefer-dist laravel/laravel your-project-name
cd your-project-name
Step 2 - Install PHPMailer:
You can add PHPMailer to your Laravel project using Composer:
composer require phpmailer/phpmailer
Step 3 - Configure Environment Variables:
In your Laravel project, open the .env
file and configure your email settings. Update the following variables with your SMTP server information:
MAIL_DRIVER=smtp
MAIL_HOST=your-smtp-host
MAIL_PORT=587
MAIL_USERNAME=your-email@example.com
MAIL_PASSWORD=your-email-password
MAIL_ENCRYPTION=tls
Step 4 - Create a Mail Class:
In Laravel, you can create a mail class using the following artisan command:
php artisan make:mail MyMail
This will create a new mail class in the app/Mail
directory.
Step 5 - Edit the Mail Class:
Open the newly created mail class, which is located at app/Mail/MyMail.php
, and modify it according to your needs.
Here's an example of a simple mail class:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class MyMail extends Mailable
{
use Queueable, SerializesModels;
public function __construct()
{
//
}
public function build()
{
return $this->view('emails.mymail')
->subject('Subject of the Email');
}
}
Step 6 - Create a Blade View:
Create a Blade view file for your email template. In this example, we'll create a view file at resources/views/emails/mymail.blade.php.
<!DOCTYPE html>
<html>
<head>
<title>Your Email Subject</title>
</head>
<body>
<p>Hello,</p>
<p>This is the content of your email.</p>
</body>
</html>
Step 7 - Sending the Email:
In your Laravel application code (e.g., a controller or a route), you can send the email like this:
use Illuminate\Support\Facades\Mail;
use App\Mail\MyMail;
// Inside your controller or route function
public function sendEmail()
{
Mail::to('edu@teknowize.com')->send(new MyMail());
return "Email sent successfully!";
}
-
Make sure to replace
edu@teknowize.com
with the actual recipient's email address. -
Run your Laravel project , and navigate to the URL or route where you written the email sending code. You should see the "Email sent successfully!" message, and the email will be sent to the recipient.