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.
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!
}