Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPMailer do not send if email is invalid

I'm using PHPMailer to send emails via contact form. When I enter an invalid email address in the input field, the email is still sent. I want to perform both client-side and server-side validations.

Does PHPMailer have a built-in validation system to check for invalid email address? If the email entered is invalid I want to return an error and not send the email.


2 Answers

The easiest and most correct way to validate email addresses is to use filter_var. Rather than relying on a patched PHPMailer, you could write a function to validate them before you send them to PHPMailer.

function validateEmailAddr($addr) {
    // note: do not attempt to write any regex to validate email addresses;
    // it will invariably be wrong
    return filter_var($addr, FILTER_VALIDATE_EMAIL);
}
like image 176
amphetamachine Avatar answered Dec 06 '25 19:12

amphetamachine


You said that you could enter something like 'sdjfygsdfisdf' and still get the email sent to you.

That's odd. Because adding any email address ('to', 'cc', 'bcc', 'replyto') in PHPMailer will go through the addOrEnqueueAnAddress() function, which does include validation checks. Adding a 'from' address uses different code, but also does validation checks.

The most obvious thing here is that you're not actually doing any error checking to trap for those errors.

Depending on whether you've got PHPMailer using exceptions or not, you might just be getting a false value returned from functions like setFrom() when you give it a bad address. If you ignore that value and carry on anyway, then yes, the email will still be sent.

So you need to add some error handling. Check for function call returning false.

However my preferred suggestion would be to switch to using exceptions for your error handler -- PHPMailer can do this just by setting a flag. This will make error handling easier, as you won't need to check for false on every single function call; just wrap the whole thing in a try catch block, and do your error handling in one go at the end.

like image 24
Spudley Avatar answered Dec 06 '25 19:12

Spudley