Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by whitelisting our website.

Validate Bad Email Address in PHP, Laravel

Hey! what’s up?

I am working on a SAAS application for my current company and facing the issue of sending emails, actually bad emails, those comply with the RFC.

So that means basic email validation is not working from the Laravel side and we are processing emails to ‘example@gmail’ like email addresses (yes RFC allow this email address, though it does not exist). Though the emails are not sending, our queue works for these emails and it consumes unnecessary resources and sends the request to the Mailgun also.

So, I did some R&D and find out this very simple solution. I hope this will help and save your time too. If yes, then don’t forget to thanks me in the comment 😉

You just need to check the email with filter_var($email, FILTER_VALIDATE_EMAIL) function.

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Send email
\Mail::send('emails.'.$template, $data, function ($message) {
$message->from('no-reply@skpaul.me', 'Laravel');
$message->to('hello@skpaul.me')->cc('work@skpaul.me');
});
} else {
// Through exception
$error = 'Invalid Email Address';
throw new Exception($error);
}

Explanation:

1. First of all we check the email address with the filter_var function.

filter_var() — Filters a variable with a specified filter. Here $email is a variable and FILTER_VALIDATE_EMAIL is the filter. Check more on php.net

2. If the email is invalid then we throw an exception with a custom message.

3. If the email is valid then we send the email through Laravel’s way. Check Laravel’s documentation for details.

If this information helps you then let me know what would you like to read next. I will try my best. And you can share this with your friends and colleagues too.

#HappyCoding

– sk paul

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Wordpress Social Share Plugin powered by Ultimatelysocial

Remote PHP, Laravel, LAMP developer experience in Oracle Service Cloud

Hi, You can subscribe to get emails
about technology hacks, tools and many more.