How to use mail function in php from localhost

The age-old question of sending emails from a PHP script on a local machine!

To use the mail() function in PHP from your localhost, you'll need to configure your PHP setup to use a mail server or a mail relay. Here are the general steps:

Option 1: Using a mail server

  1. Install a mail server software on your local machine, such as:
    • Postfix (for Linux/Mac)
    • Sendmail (for Linux/Mac)
    • Microsoft Exchange (for Windows)
  2. Configure the mail server to allow PHP to send emails. This usually involves setting up a relay host or a mail account.
  3. Update your PHP configuration file (php.ini) to use the mail server. For example, you can set the sendmail_path directive to point to the mail server's executable.

Option 2: Using a mail relay

  1. Set up a mail relay service on your local machine, such as:
    • Mailhog (for Linux/Mac)
    • Mailcatcher (for Linux/Mac)
    • Microsoft Exchange (for Windows)
  2. Configure the mail relay to forward emails to a remote mail server or a mail account.
  3. Update your PHP configuration file (php.ini) to use the mail relay. For example, you can set the sendmail_path directive to point to the mail relay's executable.

Using the mail() function

Once you've set up your mail server or mail relay, you can use the mail() function in your PHP script to send emails. The basic syntax is:

mail($to, $subject, $message, $headers);

Here's an example:

<?php
$to = '[email protected]';
$subject = 'Test email from localhost';
$message = 'This is a test email sent from localhost';
$headers = 'From: [email protected]'. "\r\n".
           'Reply-To: [email protected]'. "\r\n".
           'Content-Type: text/plain; charset=UTF-8';

mail($to, $subject, $message, $headers);
?>

Make sure to replace the placeholders ($to, $subject, $message, and $headers) with your actual email recipient, subject, message, and headers.

Troubleshooting

If you encounter issues with sending emails, check the following: