Laravel uses the SwiftMailer library for sending emails by default. The SwiftMailer is inbuilt in the Laravel. But, have you tried any other package for sending emails in Laravel? If not, then I will be showing you the PHPMailer in this post. You will already aware of the PHPMailer because in a PHP script generally, use the PHPMailer for sending an email. This is an open-source package and easy to configure and use. This package has lots of feature like you can send emails with multiple To, CC, BCC and Reply-to-address. For the security, it protects against header injection attacks. So, this is very safe to use. You can add attachments, including inline with the emails.
I have already shared lots of tutorials for sending email in Laravel 8. In this tutorial, I will be showing the step by step guide to install and use of PHPMailer example in Laravel 8. So, let’s continue with a fresh installation of Laravel 8.
Prerequisites
For creating a new project in Laravel 8, you must have the following configuration in your system.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create a Project in Laravel 8 For PHPMailer
Here, for creating a project in Laravel, I will be using the composer. You can use the Laravel installer too. Open the command prompt and hit the below command.
composer create-project --prefer-dist laravel/laravel phpmailer
Here, the Laravel 8 installation has been started. It will take a couple of minutes to ready with the installation.
After creating the project, we will be installing the PHPMailer package.
Dynamic Email Configuration in Laravel 8 For Sending Email
Install PHPMailer Package in Laravel 8
Before installing the PHPMailer package in Laravel, I will just explain some of the features of this package.
- PHPMailer is the most popular code for sending email from PHP.
- This is used by many open-source projects like WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla, and many more.
- There is the integration of SMTP support – it allows it to send email from the local mail server.
- You can send emails with multiple To, CC, BCC, and Reply-to addresses.
- This allows us to add attachments, including inline.
- It validates the email addresses automatically.
- Also, it protects against header injection attacks in the email.
- You can show the error messages in over 50 languages.
- Compatible with PHP 5.5 and later, including PHP 8.0.
- and many more.
So, this was the short description of the important features of the PHPMailer. Now, we will move to the installation of the package.
If you don’t know the exact package name then you can search for the package using the composer require command.
Here, I have entered inside the project directory and entered the package name that will gonna install.
composer require phpmailer/phpmailer
After installing the package, you can check the composer.json file available in the root of the project directory.
Here, we will setup the PHPMailer example to demonstrate it’s configuration. So, in the next step, we will be creating a controller.
Laravel 8 Client Side Form Validation Using jQuery
Create a Controller in Laravel 8
For sending emails, you will require a controller for writing the code. This controller will contain the PHPMailer Script and will configure the SMTP setting.
Therefore, create a controller. Here, the below command will create a controller with the name MailerController.php.
php artisan make:controller MailerController
Here, the controller has been created. So, at very first, I will talk about the namespace that will require to include in the controller.
PHPMailer\PHPMailer\PHPMailer;
PHPMailer\PHPMailer\Exception;
The above namespaces will be used to configure the PHPMailer SMTP. So, in the controller, we will have to add these.
Open the MailController.php file and simply paste the below snippet.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class MailerController extends Controller {
// =============== [ Email ] ===================
public function email() {
return view("email");
}
// ========== [ Compose Email ] ================
public function composeEmail(Request $request) {
require base_path("vendor/autoload.php");
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
// Email server settings
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com'; // smtp host
$mail->SMTPAuth = true;
$mail->Username = 'sender-username'; // sender username
$mail->Password = 'sender-password'; // sender password
$mail->SMTPSecure = 'tls'; // encryption - ssl/tls
$mail->Port = 587; // port - 587/465
$mail->setFrom('sender-from-email', 'sender-from-name');
$mail->addAddress($request->emailRecipient);
$mail->addCC($request->emailCc);
$mail->addBCC($request->emailBcc);
$mail->addReplyTo('sender-reply-email', 'sender-reply-name');
if(isset($_FILES['emailAttachments'])) {
for ($i=0; $i < count($_FILES['emailAttachments']['tmp_name']); $i++) {
$mail->addAttachment($_FILES['emailAttachments']['tmp_name'][$i], $_FILES['emailAttachments']['name'][$i]);
}
}
$mail->isHTML(true); // Set email content format to HTML
$mail->Subject = $request->emailSubject;
$mail->Body = $request->emailBody;
// $mail->AltBody = plain text version of email body;
if( !$mail->send() ) {
return back()->with("failed", "Email not sent.")->withErrors($mail->ErrorInfo);
}
else {
return back()->with("success", "Email has been sent.");
}
} catch (Exception $e) {
return back()->with('error','Message could not be sent.');
}
}
}
In the above snippet, you will have to add the sender details like username, password, sender email, sender name, etc. So, that you can able to send email using your own credentials. If you are using Gmail SMTP for sending an email, then you will have to create the app password for your Gmail account. Also, it will require to allow less secure app access.
After placing the above snippets, you will require to create some routes in the web.php file.
Laravel 8 Client Side Form Validation Using jQuery
Add Routes For PHPMailer
Add the below routes in the web.php file. Here, there are two routes. The first route is for loading the view from where we will send the Email. The second route is for composing email.
<?php
use App\Http\Controllers\MailerController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get("email", [MailerController::class, "email"])->name("email");
Route::post("send-email", [MailerController::class, "composeEmail"])->name("send-email");
As per the routes and the controller function, we will have to create a view. The view will contain a basic form for sending email with attachments.
Create a View For Sending Email Using PHPMailer
For sending email, I have created a view in the resources/views directory. The view name is email.blade.php. Now, you have to paste the below snippet for a basic form design.
<!doctype html>
<html lang="en">
<head>
<title>Send Email Using PHPMailer</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container pt-5 pb-5">
<div class="row">
<div class="col-xl-6 col-lg-6 col-sm-12 col-12 m-auto">
<form action="{{route('send-email')}}" method="POST" enctype="multipart/form-data">
@csrf
<div class="card shadow">
@if(Session::has("success"))
<div class="alert alert-success alert-dismissible"><button type="button" class="close">×</button>{{Session::get('success')}}</div>
@elseif(Session::has("failed"))
<div class="alert alert-danger alert-dismissible"><button type="button" class="close">×</button>{{Session::get('failed')}}</div>
@endif
<div class="card-header">
<h4 class="card-title">PHPMailer Example </h4>
</div>
<div class="card-body">
<div class="form-group">
<label for="emailRecipient">Email To </label>
<input type="email" name="emailRecipient" id="emailRecipient" class="form-control" placeholder="Mail To">
</div>
<div class="form-group">
<label for="emailCc">CC </label>
<input type="email" name="emailCc" id="emailCc" class="form-control" placeholder="Mail CC">
</div>
<div class="form-group">
<label for="emailBcc">BCC </label>
<input type="email" name="emailBcc" id="emailBcc" class="form-control" placeholder="Mail BCC">
</div>
<div class="form-group">
<label for="emailSubject">Subject </label>
<input type="text" name="emailSubject" id="emailSubject" class="form-control" placeholder="Mail Subject">
</div>
<div class="form-group">
<label for="emailBody">Message </label>
<textarea name="emailBody" id="emailBody" class="form-control" placeholder="Mail Body"></textarea>
</div>
<div class="form-group">
<label for="emailAttachments">Attachment(s) </label>
<input type="file" name="emailAttachments[]" multiple="multiple" id="emailAttachments" class="form-control">
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success">Send Email </button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Now, save and run the project to see the expected result. The above snippet will generate a form as showing below.
Create RESTful APIs in Laravel 8 Using Passport Auth
Now, try sending email to the recipient with the necessary details. Here, I have not set the validation. It is up to you, if you are creating a real project then you may set the validation for the inputs. I am just showing you here for the demo purpose.
Here, in the above screenshot, I have entered the email recipient, cc, bcc, subject, email body, and attachment.
Then, I hit the send button. In the response, I got a success message that email has been sent.
For the confirmation, I checked my mailbox and got the email with the attachment.
Also, you can see the details that I had entered in cc, subject, sender, etc.
So, everything has worked perfectly, as I was expecting.
Conclusion
In this PHPMailer example, we have implemented the functionality to send an email with an attachment using SMTP. This is the basic PHPMailer example, you can extend this demo to an advanced level. The PHPMailer is mostly used in the PHP script to send emails. It allows us to send emails from the local server. So, I hope, you will enjoy this post. For any kind of issue regarding this tutorial, don’t forget to write in the comment section.
mariam ja says
hello sir
can you guide on how to include view file in the body of php mailer in laravel.
as i need to send templates and often need to pass some array of data to display in these templates
Umesh Rana says
Hi Mariam,
Thank you for raising your query.
Instead of this –
$mail->Body = $request->emailBody;
You can pass the entire HTML template as a parameter as like this –
$mail->Body = "<!doctype html><html>
<head>
<title>The SMS Template Title</title>
</head>
<body>
<!-- Your HTML template will go here -->
</body>
</html>";
Also, if you want to pass variables with this template then you can pass it easily.
"<div class='container'>
<h4>Hello ".$someName.", </h4>
<p>Thanks for reaching out to me. </p>
</div>"
For the template design, you will have to pass inline CSS. Here external CSS will not work.
mariam ja says
thank you so much for your reply
nicolae says
hello sir
Thanks for your post. This is much helpful for me.
and Can I get full source code? if you have any git repository, Please share me Thanks Nicolae
David says
Hello Sir,
I did not receive any email after the execution of the code only the page will be reloaded and not show any error or message.
Umesh Rana says
I guess you missed some steps. Please follow the above steps correctly.