Monday, May 24, 2010

PHP localhost mail function

To make Ubuntu PHP localhost mail function work, using PHP to send mail from localhost is easy. First, you need to install some PEAR mail packages.

In terminal, run the following command one by one:
sudo pear install mail
sudo pear install Net_SMTP
sudo pear Auth_SASL
sudo pear install mail_mime

After installing the pear packages, you need to install and configure postfix, first, run the following command to install postfix:

sudo apt-get install postfix

after installation, a configuration window will be displayed, you need to configure it:

Step 1: Choose Internet Site

Step 2: Enter localhost at the input area

For the rest of the steps, just follow the default settings. After complete the configuration, it’s time to test the PHP script. Create a PHP file called sendmail.php at your localhost, and copy and paste the code below into it (remember to change the email addresses to yours)

include('Mail.php');
include('Mail/mime.php');
// Constructing the email
$sender = "shi ";
$recipient = "Leigh ";
$subject = "Test Email";
$text = 'This is a text message.';
$html = '

This is a html message

';
$crlf = "\n";
$headers = array(
'From' => $sender,
'Return-Path' => $sender,
'Subject' => $subject
);
// Creating the Mime message
$mime = new Mail_mime($crlf);
// Setting the body of the email
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
// Set body and headers ready for base mail class
$body = $mime->get();
$headers = $mime->headers($headers);
// SMTP params
$smtp_params["host"] = "localhost"; // SMTP host
$smtp_params["port"] = "25"; // SMTP Port (usually 25)
// Sending the email using smtp
$mail =& Mail::factory("smtp", $smtp_params);
$result = $mail->send($recipient, $headers, $body);
if($result == 1)
{
echo("Your message has been sent!");
}
else
{
echo("Your message was not sent: " . $result);
}
?>

No comments:

Post a Comment