Search code examples
phpemailsmtppear

Using PHP Pear mail :Failed to add recipient:


I am using Php Pear mail for sending an attachment to the user who fills out a form. If I hard code the "to email" address it works fine. But when I use $to = $_POST['email'] ; I get the following error.

Failed to add recipient: @localhost [SMTP: Invalid response code received from server (code: 501, response: <@localhost>: no local part)]

<?php

require_once 'Mail.php'; 
require_once 'Mail/mime.php';




$from = "[email protected]";
$to = $_POST['email'] ; 
$subject = 'Free Diagnostic Test Coupon';

$headers = array ('From' => $from,'To' => $to, 'Subject' => $subject);

$text = 'Please find attached the coupon';// text and html versions of email.
$html = '<html><body>Please find attached the coupon</body>        </html>';

$file = 'img/coupon.jpg'; // attachment
$crlf = "\n";

$mime = new Mail_mime($crlf);
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, 'image/jpeg');

//do not ever try to call these lines 
$host = "host";
$username = "username";
$password = "password";
in reverse order
$body = $mime->get();
$headers = $mime->headers($headers);
$smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true,
 'username' => $username,'password' => $password));

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

if (PEAR::isError($mail)) {
  echo("<p>" . $mail->getMessage() . "</p>");
}
else {
  echo("<p>Message successfully sent!</p>");
}
?>

Any help will be appreciated.


Solution

  • Check your code by adding the top of it.

    error_reporting(E_ALL); ini_set('display_errors', '1');