tags:

views:

838

answers:

2

I'm trying to use PHPMailer for a small project, but I'm a bit confused about error handling with this software. Hoping someone has experience with it. When I've set up an email and I use:

$result = $mail->Send();

if(!$result) {
    // There was an error
    // Do some error handling things here
} else {
    echo "Email successful";
}

Which works fine, more or less. The problem is when there's an error, PHPMailer also seems to echo the error out, so if there's a problem, it just sends that info directly to the browser, essentially breaking any error handling I"m trying to do.

Is there a way to silence these messages? Its not throwing an exception, its just printing out the error, which in my test case is:

invalid address: @invalid@email You must provide at least one recipient email address.

Its meant to be an error, but it should be residing in $mail->ErrorInfo; not being echo'd out by the software.

+4  A: 

Hi,

PHPMAiler uses Exceptions. Try to adopt the following code:

require_once '../class.phpmailer.php';

$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch

try {
  $mail->AddReplyTo('[email protected]', 'First Last');
  $mail->AddAddress('[email protected]', 'John Doe');
  $mail->SetFrom('[email protected]', 'First Last');
  $mail->AddReplyTo('[email protected]', 'First Last');
  $mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
  $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
  $mail->MsgHTML(file_get_contents('contents.html'));
  $mail->AddAttachment('images/phpmailer.gif');      // attachment
  $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
  $mail->Send();
  echo "Message Sent OK\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}
henchman
i presume you are using this version (or similar): http://www.koders.com/php/fidCC8AE076B52AE98944DA9CB47C07261A65A099D2.aspx?s=phpmailerException+#L416open your file in texteditor and comment out all line which contain the word echo (5 lines in the online version). Then, only the exceptions will be thrown.
henchman
I had already tried catching it with exceptions, the part I had missed was `new PHPMailer(true)` which actually enables the exceptions. Thank you for your help.
Stomped
A: 

i want to silence all the error messages which r printed in phpmailer please help

vijay