How to Replace PHP mail() with SMTP in Laravel Print

  • 0

If you're using Laravel with Prabhu Host and want to ensure your emails are reliably delivered, it's recommended to switch from the default PHP mail() function to SMTP. SMTP provides better authentication and security for outgoing mail, and works seamlessly with Laravel.

Here’s a step-by-step guide to implement SMTP-based email sending in Laravel:

Step 1: Install SwiftMailer (if using older Laravel versions)

Most Laravel versions already include SwiftMailer by default. If it's not installed, you can add it manually:

      composer require swiftmailer/swiftmailer

For Laravel 9 and above, Laravel uses Symfony Mailer instead of SwiftMailer, so this step might be unnecessary.

Step 2: Configure SMTP in the .env File

Open your Laravel project’s .env file and update the following lines with your SMTP credentials:

MAIL_MAILER=smtp
MAIL_HOST=smtp.yourmailserver.com
MAIL_PORT=587
MAIL_USERNAME=your_email@yourdomain.com
MAIL_PASSWORD=your_email_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your_email@yourdomain.com
MAIL_FROM_NAME="Your App Name"
 
Example for Gmail:
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_gmail_app_password
MAIL_ENCRYPTION=tls
 
Use an App Password for Gmail instead of your regular login password.

Step 3: Update Laravel Mail Configuration

In config/mail.php, make sure the mailer is using SMTP by default:

'driver' => env('MAIL_MAILER', 'smtp'),

You may also review the mailers array and ensure smtp is configured properly if you're on Laravel 8 or later.

Step 4: Update Your Email-Sending Code

Use Laravel’s Mail facade to send emails instead of the native mail() function.

use Illuminate\Support\Facades\Mail;
use App\Mail\YourMailClass;

Mail::to('recipient@example.com')->send(new YourMailClass($data));

Replace YourMailClass with your actual Mailable class.

Generate a custom Mailable class using Artisan:
php artisan make:mail YourMailClass
 
This will create a file in app/Mail/YourMailClass.php, where you can define the email subject, body, and view.
 

Test Your SMTP Setup

To confirm everything works:

  • Trigger an email send from your application.

  • Check your inbox or use a test email address.

  • Check Laravel logs (storage/logs/laravel.log) for errors if no email is received.

Conclusion

Replacing the PHP mail() function with SMTP in Laravel improves your email deliverability and ensures better security. Whether you're using Gmail, Outlook, Zoho, or your Prabhu Host business email, Laravel's SMTP integration provides a robust and professional solution for all your email needs.

 Need help configuring SMTP? Contact Prabhu Host support for expert assistance.


Was this answer helpful?
Back