How to mail on localhost by php

The eternal question!

Mailing from a local development environment (localhost) using PHP can be a bit tricky, as most mail servers are configured to only accept mail from specific IP addresses or domains. However, there are a few ways to achieve this:

Method 1: Using a mail client like Mailhog

Mailhog is a popular tool that allows you to capture and inspect emails sent from your local development environment. You can install Mailhog using Composer:

composer require mailhog/mailhog

Once installed, start the Mailhog server:

php artisan mailhog:start

This will start a mail server that listens on localhost:8025. You can then configure your PHP script to send mail to localhost:8025 instead of a real mail server.

Method 2: Using a virtual mail server like Maildev

Maildev is another tool that allows you to test and inspect emails sent from your local development environment. You can install Maildev using npm:

npm install -g maildev

Once installed, start the Maildev server:

maildev

This will start a mail server that listens on localhost:1025. You can then configure your PHP script to send mail to localhost:1025 instead of a real mail server.

Method 3: Using a PHP mail library like SwiftMailer

SwiftMailer is a popular PHP mail library that allows you to send emails using a variety of transport mechanisms, including SMTP, Sendmail, and PHP's built-in mail function. You can install SwiftMailer using Composer:

composer require swiftmailer/swiftmailer

Once installed, you can configure SwiftMailer to use a virtual mail server like Mailhog or Maildev. For example:

use SwiftMailer\SwiftMailer;

$mailer = new SwiftMailer();
$mailer->setTransport(new Swift_SendmailTransport('mailhog:8025'));

Method 4: Using a PHP mail library like PHPMailer

PHPMailer is another popular PHP mail library that allows you to send emails using a variety of transport mechanisms, including SMTP, Sendmail, and PHP's built-in mail function. You can install PHPMailer using Composer:

composer require phpmailer/phpmailer

Once installed, you can configure PHPMailer to use a virtual mail server like Mailhog or Maildev. For example:

use PHPMailer\PHPMailer\PHPMailer;

$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'localhost';
$mail->Port = 8025;

In all cases, you'll need to configure your PHP script to use the virtual mail server's IP address and port number instead of a real mail server's IP address and port number.

Remember to update your PHP script's mail configuration to point to the virtual mail server, and you should be able to send and receive emails from your local development environment.