Can we send mail from localhost in php ubuntu

A classic question!

By default, PHP's mail() function uses the system's default mail server to send emails. On Ubuntu, this is usually configured to use a local mail server, such as sendmail or postfix.

To send mail from a PHP script running on your local machine (localhost), you'll need to configure your system to allow PHP to send emails. Here are the general steps:

Option 1: Using sendmail

  1. Install sendmail if you haven't already: sudo apt-get install sendmail
  2. Configure PHP to use sendmail as the mail transport agent (MTA): Edit the /etc/php5/apache2/php.ini file (or the equivalent for your PHP version) and add the following lines:
    [mail function]
    ; For Win32 only.
    SMTP = localhost
    smtp_port = 25
  3. Restart your Apache server: sudo service apache2 restart

Option 2: Using postfix

  1. Install postfix if you haven't already: sudo apt-get install postfix
  2. Configure PHP to use postfix as the MTA: Edit the /etc/php5/apache2/php.ini file (or the equivalent for your PHP version) and add the following lines:
    [mail function]
    ; For Win32 only.
    SMTP = localhost
    smtp_port = 25
  3. Restart your Apache server: sudo service apache2 restart

Testing the setup

Create a simple PHP script to test the mail sending:

<?php
mail('[email protected]', 'Test Subject', 'This is a test email');
?>

Run the script and check your email client for the received email.

Additional tips