How to send email using pear mail is php's mail function doesnt work or gives an error?

PHP mail function is some times disabled by hosts for various anti spam and security reasons. This is cause it can be used to send anonymous email and is vulnerable to form injections.

You can still use a much better mailing function PEAR:mail. Below is a sample code which you can use in any PHP file you create. Just follow the simple instructions below:

  1. Replace the variables in the following code.
  2. Use your email address/account created on same server.
  3. You dont need to have the file Mail.php, it is already installed as PEAR package

<?php
require_once "Mail.php";

/**************************************************
EDIT the following variables for your own use
***************************************************/
$from = "Sender <sender@example.com>";
$to = "Recipient <recipient@example.com>";

$subject = "Hi!"; //type in subject here

$host = "mail.example.com"; // Your domain
$username = "smtp_username"; // Your user / full email address
$password = "smtp_password"; // Password to your email address

 

/**************************************************
***************************************************/

$body = "";

foreach($_POST as $a => $b)
{
$body .= $a .": ". $b . "\n";
}

$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
/**************************************************
ERROR MESSAGE
***************************************************/
?>

<p> <? echo $mail->getMessage(); ?> </p>
<?
/**************************************************/
} else {
/**************************************************
SUCCESS MESSAGE
***************************************************/
?>
<p>Message successfully sent!</p>
<?
/**************************************************/
}
?>