How to send email from localhost using mail function

To send an email from a localhost using the mail() function in PHP, 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 localhost, such as:
    • Postfix (for Linux)
    • Sendmail (for Linux)
    • Microsoft Exchange (for Windows)
  2. Configure the mail server to listen on a specific port (e.g., 25).
  3. Update your PHP configuration to use the mail server:
    • In your php.ini file, set the SMTP and smtp_port settings to the values of your mail server. For example:
      SMTP = localhost
      smtp_port = 25
  4. Restart your web server (e.g., Apache or Nginx) to apply the changes.

Option 2: Using a mail relay

  1. Set up a mail relay service on your localhost, such as:
    • Mailhog (for Linux and Windows)
    • Mailcatcher (for Linux and Windows)
  2. Configure the mail relay to listen on a specific port (e.g., 1025).
  3. Update your PHP configuration to use the mail relay:
    • In your php.ini file, set the SMTP and smtp_port settings to the values of your mail relay. For example:
      SMTP = localhost
      smtp_port = 1025
  4. Restart your web server (e.g., Apache or Nginx) to apply the changes.

Example PHP code

Here's an example PHP code that sends an email using the mail() function:

<?php
$to = '[email protected]';
$subject = 'Test email';
$message = 'This is a test email';

$headers = 'From: [email protected]'. "\r\n".
           'Reply-To: [email protected]'. "\r\n".
           'MIME-Version: 1.0'. "\r\n".
           'Content-Type: text/plain; charset=UTF-8';

if (mail($to, $subject, $message, $headers)) {
    echo 'Email sent successfully!';
} else {
    echo 'Error sending email!';
}
?>

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

Troubleshooting

If you encounter issues sending emails, check the following: