How to send mail in php from localhost

To send mail from PHP on your localhost, you'll need to configure your PHP setup to use a mail server or a mail transport agent (MTA) that can send emails. Here are the general steps:

Option 1: Using PHP's built-in mail function

  1. Make sure your PHP installation is configured to use a mail server. You can check this by running the following command in your terminal:
    php -r "echo ini_get('SMTP');"

    If the output is empty or null, you'll need to configure your PHP installation to use a mail server.

  2. Create a PHP script that uses the mail() function to send an email. 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".
            'X-Mailer: PHP/'. phpversion();

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

3. Save the script as a PHP file (e.g., `sendmail.php`) and run it using your web server (e.g., Apache, Nginx).

**Option 2: Using a mail transport agent (MTA) like Sendmail or Postfix**

1. Install an MTA like Sendmail or Postfix on your system. For example, on Ubuntu-based systems, you can install Sendmail using:

sudo apt-get install sendmail

2. Configure your MTA to use a mail server. For example, you can edit the Sendmail configuration file (`/etc/sendmail.cf`) to specify a mail server:

sudo nano /etc/sendmail.cf

Add the following lines to the end of the file:

define(SMART_HOST',smtp.gmail.com:587') define(RELAYHOST',smtp.gmail.com:587')

3. Restart the Sendmail service:

sudo service sendmail restart

4. Create a PHP script that uses the `mail()` function to send an email. The script will use the MTA to send the email.
```php
<?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".
           'X-Mailer: PHP/'. phpversion();

mail($to, $subject, $message, $headers);
?>
  1. Save the script as a PHP file (e.g., sendmail.php) and run it using your web server (e.g., Apache, Nginx).

Troubleshooting tips