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
- Install
sendmail
if you haven't already:sudo apt-get install sendmail
- 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
- Restart your Apache server:
sudo service apache2 restart
Option 2: Using postfix
- Install
postfix
if you haven't already:sudo apt-get install postfix
- 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
- 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
- Make sure your PHP script has the necessary permissions to write to the mail queue (usually
/var/spool/postfix
or/var/spool/sendmail
). - If you're using a firewall, ensure that port 25 (SMTP) is open.
- You can also use a third-party mail library like SwiftMailer or PHPMailer to send emails from your PHP script.