EmailValidator - PHP Email address validator

Last update: May 26, 2022

EmailValidator

Build Status Code Quality Test Coverage

A library for validating emails against several RFC.

Supported RFCs

This library aims to support RFCs:

Supported versions

Curent major version with full support is v3

Version Released EOL Only critical bug fixes Full
v3.x 2020/12/29 - X X
v2.1.x 2016/05/16 01/2022 X
v1.2 2013/19/05 YES

Requirements

Note: PHP version upgrades will happen to accomodate to the pace of major frameworks. Minor versions bumps will go via minor versions of this library (i.e: PHP7.3 -> v3.x+1). Major versions will go with major versions of the library

Installation

Run the command below to install via Composer

composer require egulias/email-validator

Getting Started

EmailValidatorrequires you to decide which (or combination of them) validation/s strategy/ies you'd like to follow for each validation.

A basic example with the RFC validation

<?php

use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;

$validator = new EmailValidator();
$validator->isValid("[email protected]", new RFCValidation()); //true

Available validations

  1. RFCValidation: Standard RFC-like email validation.
  2. NoRFCWarningsValidation: RFC-like validation that will fail when warnings* are found.
  3. DNSCheckValidation: Will check if there are DNS records that signal that the server accepts emails. This does not entails that the email exists.
  4. MultipleValidationWithAnd: It is a validation that operates over other validations performing a logical and (&&) over the result of each validation.
  5. MessageIDValidation: Follows RFC2822 for message-id to validate that field, that has some differences in the domain part.
  6. Your own validation: You can extend the library behaviour by implementing your own validations.

*warnings: Warnings are deviations from the RFC that in a broader interpretation are acceptded.

<?php

use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\DNSCheckValidation;
use Egulias\EmailValidator\Validation\MultipleValidationWithAnd;
use Egulias\EmailValidator\Validation\RFCValidation;

$validator = new EmailValidator();
$multipleValidations = new MultipleValidationWithAnd([
    new RFCValidation(),
    new DNSCheckValidation()
]);
//ietf.org has MX records signaling a server with email capabilites
$validator->isValid("[email protected]", $multipleValidations); //true

Additional validations

Validations not present in the RFCs

  1. SpoofCheckValidation: Will check for multi-utf-8 chars that can signal an erroneous email name.

How to extend

It's easy! You just need to implement EmailValidation and you can use your own validation.

Contributing

Please follow the Contribution guide. Is short and simple and will help a lot.

Other Contributors

(You can find current contributors here)

As this is a port from another library and work, here are other people related to the previous one:

  • Ricard Clau @ricardclau: Performance against PHP built-in filter_var (v2 and earlier)
  • Josepf Bielawski @stloyd: For its first re-work of Dominic's lib
  • Dominic Sayers @dominicsayers: The original isemail function

License

Released under the MIT License attached with this code.

GitHub

https://github.com/egulias/EmailValidator
Comments
  • 1. Failing SwiftMailer test after upgrade to v3

    Hi all, I hope this is the right place to ask this question as I couldn't immediately find something in the contributing guidelines. Appreciating if anyone could answer a question I have about a failing SwiftMailer test after upgrading to v3.

    I've tried patching SwiftMailer to v3 which mostly went super smooth and didn't require any code changes (thanks!). But one test is now failing for EmailValidator v3:

    https://github.com/swiftmailer/swiftmailer/blob/master/tests/unit/Swift/Mime/Headers/IdentificationHeaderTest.php#L118

    With the following message:

    1) Swift_Mime_Headers_IdentificationHeaderTest::testIdRightCanBeDotAtom
    Swift_RfcComplianceException: Invalid ID given <[email protected]+&%$.d>
    
    /Users/driesvints/Sites/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php:183
    /Users/driesvints/Sites/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php:128
    /Users/driesvints/Sites/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php:99
    /Users/driesvints/Sites/swiftmailer/tests/unit/Swift/Mime/Headers/IdentificationHeaderTest.php:118
    

    The exception is being thrown here:

    https://github.com/swiftmailer/swiftmailer/blob/master/lib/classes/Swift/Mime/Headers/IdentificationHeader.php#L183

    I guess my main question is why [email protected]+&%$.d isn't a valid email address anymore in EmailValidator v3? I'm not very familiar with all of the rules from RFC 2822 so I don't immediately see what's wrong here.

    Reviewed by driesvints at 2021-01-22 15:26
  • 2. Proposal: 2.0 API

    Hi,

    I forked your lib today as I was planning to investigate it for #93. I think before adding new features, some core components need to be improved first, api-wise, and imho of course ;-) I saw you already did some work on errors & warnings. I'm talking master here.

    The Lexer

    I don't want to discuss any implementation/spec details here, im not an email expert nor a lexer expert. As its API is provided by doctrine we should keep this as is.

    The Parser

    This one is a bit weird i think, basicly there are 3 parsers, however api- and implementation-wise they are all a bit different..

    EmailParser

    • Domain part is set using EmailParser::$domainParser, i.e. using the lexer, which is good.
    • Local part is set using simple explode which somehow bypasses this test, wtf?
    • Returns parsed parts which is good.

    LocalPart

    • Doesn't use argument $localPart in parse(), it relies on EmailParser calling setInput() on the same lexer instance previously.
    • Returns no parsed part(s) nor does it allow for getLocalPart(), the logic is done back in EmailParser::parse() but that is wrong for using explode.. im lost here.

    DomainPart

    • Same flaw as LocalPart (argument $domainPart is unused in parse()).
    • Returns no parsed part(s) but allows for getDomainPart().

    Proposal

    I think the problem is LocalPart and DomainPart are not parsers itself, but they modify the Lexer state, to make the actual parser, i.e. EmailParser, work. Then again DomainPart does work as a parser. Point is.. i really think we should use the lexer/local part parser for getting the "correct" local part, i just dont get this explode thingy. I guess the individual parts as result from the parser are just unused/untested. This should work! So...;

    • Make LocalPart a parser like DomainPart, i.e. allow for getLocalPart() and use it in EmailParser
      • Point is.. if we have standalone parsers, they should work standalone. I.e. all setting its input on the lexer.
    • Move all the logic to EmailParser, i.e. perhaps it's a bit over-engineered
    • Make it part of the lexer component, i.e. just modify state on the lexer and grab the parts from it in the parser
    • Make it lexers, i.e. LocalPartLexer only reads from start to @ whereas DomainPartLexer reads from @ to end

    The Validator

    Later :) lets focus on the parser first.

    Any thoughts? :smile:

    Reviewed by ro0NL at 2016-04-30 20:21
  • 3. dns_get_record(): DNS Query failed

    dns_get_record('[email protected]', DNS_MX + DNS_A + DNS_AAAA);
    

    I got "Warning: dns_get_record(): DNS Query failed".

    I suggest add @ to dns_get_record() in https://github.com/egulias/EmailValidator/blob/840d5603eb84cc81a6a0382adac3293e57c1c64c/src/Validation/DNSCheckValidation.php#L121

    My environment:

    • Windows 10
    • PHP 7.3.12 (cli) (built: Nov 19 2019 13:58:02) ( ZTS MSVC15 (Visual C++ 2017) x64 )
    Reviewed by marliotto at 2020-08-19 07:13
  • 4. Invalid email appears valid

    $validator = new \Egulias\EmailValidator\EmailValidator();
    
    if ($validator->isValid('test  [email protected]')) {
        echo 'valid';
    }
    

    Acording to the validator this email is valid.

    Reviewed by v3labs at 2014-11-14 22:09
  • 5. Email existence validation

    As a validation that checks for the existence of a given mailbox, not just the availability of the server to respond to SMTP request. E.g https://github.com/elliotttf/valid-mails

    Reviewed by egulias at 2016-08-31 22:17
  • 6. version 1.2.6 requires doctrine/lexer dev-master

    if i install the version 1.2.6 have i the following problem:

    Problem 1 - Installation request for egulias/email-validator v1.2.6 -> satisfiable by egulias/email-validator[1.2.6]. - egulias/email-validator 1.2.6 requires doctrine/lexer dev-master -> no matching package found. Problem 2 - egulias/email-validator 1.2.6 requires doctrine/lexer dev-master -> no matching package found. - tubssp/aura 2.5.x-dev requires egulias/email-validator v1.2.6 -> satisfiable by egulias/email-validator[1.2.6]. - Installation request for tubssp/aura 2.5.x-dev -> satisfiable by tubssp/aura[2.5.x-dev].

    but the version 1.X of lexer ist needet from others: Problem 1 - The requested package doctrine/lexer could not be found in any version, there may be a typo in the package name. Problem 2 - Installation request for tubssp/aura 2.5.x-dev -> satisfiable by tubssp/aura[2.5.x-dev]. - tubssp/aura 2.5.x-dev requires doctrine/lexer master -> no matching package found. Problem 3 - Installation request for egulias/email-validator v1.2.6 -> satisfiable by egulias/email-validator[1.2.6]. - egulias/email-validator 1.2.6 requires doctrine/lexer dev-master -> no matching package found. Problem 4 - doctrine/orm v2.4.6 requires doctrine/dbal ~2.4 -> satisfiable by doctrine/dbal[v2.4.3, v2.4.0, v2.4.1, v2.4.2]. - doctrine/orm v2.4.6 requires doctrine/dbal ~2.4 -> satisfiable by doctrine/dbal[v2.4.3, v2.4.0, v2.4.1, v2.4.2]. - doctrine/dbal v2.4.3 requires doctrine/common ~2.4 -> satisfiable by doctrine/common[v2.4.2, v2.4.0, v2.4.1]. - doctrine/dbal v2.4.0 requires doctrine/common ~2.4 -> satisfiable by doctrine/common[v2.4.2, v2.4.0, v2.4.1]. - doctrine/dbal v2.4.1 requires doctrine/common ~2.4 -> satisfiable by doctrine/common[v2.4.2, v2.4.0, v2.4.1]. - doctrine/dbal v2.4.2 requires doctrine/common ~2.4 -> satisfiable by doctrine/common[v2.4.2, v2.4.0, v2.4.1]. - doctrine/dbal v2.4.3 requires doctrine/common ~2.4 -> satisfiable by doctrine/common[v2.4.2, v2.4.0, v2.4.1]. - doctrine/common v2.4.2 requires doctrine/lexer 1.* -> no matching package found. - doctrine/common v2.4.2 requires doctrine/lexer 1.* -> no matching package found. - doctrine/common v2.4.1 requires doctrine/lexer 1.* -> no matching package found. - doctrine/common v2.4.0 requires doctrine/lexer 1.* -> no matching package found. - Installation request for doctrine/orm v2.4.6 -> satisfiable by doctrine/orm[v2.4.6].

    Reviewed by ickbinhier at 2014-12-01 07:17
  • 7. New release after 2.1.18 is 2.19.0

    The release does have some new validation in it, so it might have been 2.2.0 or 2.1.19

    I guess this was an accidental error, numbering the release 2.19.0

    It is too late now, and does not do any harm - 2.2.* 2.3.* through 2.18.* will just never exist.

    I have raised this issue just to point this out, and so that when making the next release someone will continue the numbering from here - 2.19.1... then 2.20.0 - please close this issue after acknowledging.

    Reviewed by phil-davis at 2020-08-09 09:21
  • 8. Prevent some DNS checks when not allowing local domains

    I find quite some of the failed validations I have in production are people just forgetting a dot in the domain part. As I don't allow local domains for the email address this helps in not having to make a more expensive DNS check with a long timeout.

    Reviewed by lode at 2018-04-09 21:32
  • 9. Small contribution - code readability improvements

    Hi,

    Thanks for your code !

    As a very small contribution to this library, I would like to propose some code readability/maintainability improvements. This will not revolutionize anything, but hope this is good enough.

    I tried to run tests but there was some errors on DSNCheckValidationTest. This error was before and still returned by PHPUnit. May be linked to #287 ?

    1) Egulias\EmailValidator\Tests\EmailValidator\Validation\DNSCheckValidationTest::testNoDNSError
    Failed asserting that two objects are equal.
    --- Expected
    +++ Actual
    @@ @@
     Egulias\EmailValidator\Result\InvalidEmail Object (
         'token' => ''
    -    'reason' => Egulias\EmailValidator\Result\Reason\NoDNSRecord Object &0000000000d01c93000000002db9369d ()
    +    'reason' => Egulias\EmailValidator\Result\Reason\UnableToGetDNSRecord Object &0000000000d01c94000000002db9369d ()
     )
    

    Hope this will not block this PR. This PR doesn't change EmailValidator functionally.

    Regards, Julien

    Reviewed by JuGid at 2021-10-17 23:26
  • 10. Enabling psalm on php >= 7.1, fixing #125, #168, #169, partially fixing #177

    • re: 210ac3c & da2e0c6, there's an @psalm-suppress or two in there rather than a baseline file because the older versions of psalm required for php < 7 consider the baseline attribute invalid so that'd be best put off until you make the decision to drop support for php 5 in a given release.
    • c504af2 only partially resolves #177 because the SpoofChecker class isn't polyfilled. The options there would be to find a polyfill just for SpoofChecker, or to fork out the SpoofCheckValidation class into a package that explicitly requires ext-intl:*
    • 6812a28 & 02a6193 were done for value-added giggles.
    Reviewed by SignpostMarv at 2019-01-19 22:21
  • 11. Class 'Doctrine\\Common\\Lexer\\AbstractLexer' not found in /var/www/html/new/swift/EmailValidator/EmailValidator/EmailLexer.php on line 7

    I want to send email using swiftmailer for that I've installed swiftmailer (git clone https://github.com/swiftmailer/swiftmailer.git) I also installed EmailValidator (git clone https://github.com/egulias/EmailValidator.git)

    But, I'm getting the error Class 'Doctrine\Common\Lexer\AbstractLexer not found in EmailLexer.php on line 7. To solve this, I'd installed lexer (git clone https://github.com/doctrine/lexer.git) in EmailValidator/EmailValidator folder but, it didn't helped me, so later I deleted that lexer folder.

    Can anyone please tell me, how to fix this?

    My folder structure is screenshot from 2017-08-30 12-06-32

    My sendemail.php is: screenshot from 2017-08-30 12-14-17

    Reviewed by ssnatu at 2017-08-30 11:12
  • 12. Undefined array key "type"

    I'm getting Undefined array key "type" error from time to time at production:

        private function validateMxRecord($dnsRecord) : bool
        {
            if ($dnsRecord['type'] !== 'MX') {
                return true;
            }
    

    Relevant trace:

    #86 /vendor/egulias/email-validator/src/Validation/DNSCheckValidation.php(170): Egulias\EmailValidator\Validation\DNSCheckValidation::validateMxRecord
    #85 /vendor/egulias/email-validator/src/Validation/DNSCheckValidation.php(150): Egulias\EmailValidator\Validation\DNSCheckValidation::validateDnsRecords
    #84 /vendor/egulias/email-validator/src/Validation/DNSCheckValidation.php(110): Egulias\EmailValidator\Validation\DNSCheckValidation::checkDns
    #83 /vendor/egulias/email-validator/src/Validation/DNSCheckValidation.php(86): Egulias\EmailValidator\Validation\DNSCheckValidation::isValid
    #82 /vendor/egulias/email-validator/src/Validation/MultipleValidationWithAnd.php(66): Egulias\EmailValidator\Validation\MultipleValidationWithAnd::isValid
    #81 /vendor/egulias/email-validator/src/EmailValidator.php(37): Egulias\EmailValidator\EmailValidator::isValid
    

    Email validated is [email protected]. It looks like dns_get_record might return info element w/o type specified.

    Reviewed by samdark at 2022-05-23 11:53
  • 13. [email protected] marked as invalid, but should be valid according to RFC 2822

    A dot before @ ([email protected]) will be marked as invalid.

    ~~Browsers (Chrome) and Symfony Validators mark them as valid too.~~

    • The Symfony-Validator can be configured to use "HTML5" or "Strict" Validation. Strict uses this validator
    • Browsers use "HTML5" Validation

    Nevertheless... As far as I can tell, according to RFC 2822 it should be valid.

    Reviewed by FranzBruckner at 2022-03-02 10:02
  • 14. Email "[email protected]#" is valid?

    <?php
    
    use Egulias\EmailValidator\EmailValidator;
    use Egulias\EmailValidator\Validation\RFCValidation;
    
    $validator = new EmailValidator();
    
    //  "egulias/email-validator": "2.1.25"
    $validator->isValid('[email protected]#', new RFCValidation()); //true
    
    //  "egulias/email-validator": "3.1.2"
    $validator->isValid('[email protected]#', new RFCValidation()); //false
    

    HTML5 validator is saying also that [email protected]# is wrong.

    Reviewed by dadscript at 2022-02-11 09:37
  • 15. Compile Error! Declaration of Egulias\EmailValidator\Validation\MessageIDValidation::getError()...

    Hi and congrats on this software,

    Around October 2021 emails stopped sending at all. Fuel PHP just gives it's "Ooops! Something went wrong". On my dev site though I get the below even after removing and doing a composer re-install. :

    Compile Error! ErrorException [ Compile Error ]: Declaration of Egulias\EmailValidator\Validation\MessageIDValidation::getError() must be compatible with Egulias\EmailValidator\Validation\EmailValidation::getError(): Egulias\EmailValidator\Result\InvalidEmail

    DOCROOT/fuel/vendor/egulias/email-validator/src/Validation/MessageIDValidation.php @ line 10

    class MessageIDValidation implements EmailValidation { ....

    Backtrace COREPATH/bootstrap.php @ line 80

    Many thanks, Robert

    Reviewed by robert-pod-trak at 2022-01-12 12:29
Laravel Disposable Email Validator
 Laravel Disposable Email Validator

Laravel Disposable Email Validator Prevent users from registrering with a disposable email addresses! Table of Contents Installation Usage Translation

Nov 4, 2021
🥳🔐 This package is a Laravel package that checks if an email address is a spammer
🥳🔐 This package is a Laravel package that checks if an email address is a spammer

This package is a Laravel package that checks if an email address is a spammer. It verifies your signups and form submissions to confirm that they are legitimate.

May 19, 2022
Trigger email failures to assert what happens on your Laravel Application when an email fails to send

Laravel Email Failer composer require --dev rogervila/laravel-email-failer About Trigger email failures to assert what happens on your Laravel Applica

Nov 24, 2021
laravel-model-validator

laravel-model-validator This is a simple validator. The validator can be created by command. The validator has all common table column constraint, eg:

May 22, 2022
This is a simple url bot validator made with laravel and react

?? This is a simple URL validator. Used Technologies React - Javascript framework Laravel - PHP framework Mysql - Relational database Installation Ins

Oct 27, 2021
Laravel Common Password Validator

laravel-common-password-validator Laravel Common Password Validator An optimized and secure validator to check if a given password is too common. By d

Nov 6, 2021
Laravel Dutch Phone Number Validator
 Laravel Dutch Phone Number Validator

Laravel Dutch Phone Number Validator Validate if the given phone number is a valid Dutch phone number Table of Contents Installation Usage Translation

Nov 15, 2021
A simple validator package to check if the given zipcode has a valid Dutch zipcode format
A simple validator package to check if the given zipcode has a valid Dutch zipcode format

Laravel Dutch Zipcode Validator A simple validator package to check if the given zipcode has a valid Dutch zipcode format Table of Contents Installati

Nov 15, 2021
Simple address and contact management for Laravel with automatically geocoding to add longitude and latitude

Laravel Addresses Simple address and contact management for Laravel with automatically geocoding to add longitude and latitude. Installation Require t

Apr 4, 2022
Email validation service in PHP

Email validation service Email validation service in PHP using Laravel 8. Validation features Domain Regular Expression Smtp Txt records Installing de

Oct 30, 2021
Email-flooder - A CLI flooder e-mail tool, made in PHP.
Email-flooder - A CLI flooder e-mail tool, made in PHP.

E-mail flooder (PHP 8.0.13) You can send emails to any server, however the request must come from Gmail. (Remember to enable less secure apps to be ab

Dec 17, 2021
A package to validate email domains in a user registration form
A package to validate email domains in a user registration form

This package allows to define a subset of allowed email domains and validate any user registration form with a custom rule.

May 20, 2022
Simple transactional email classes/templates for Laravel 5 mailables
Simple transactional email classes/templates for Laravel 5 mailables

Tuxedo Tuxedo is an easy way to send transactional emails with Laravel's Mail classes, with the templates already done for you. Contents Installation

Jan 1, 2022
A package to validate email domains in a user registration form
A package to validate email domains in a user registration form

Laravel Email Domain Rule This package allows to define a subset of allowed email domains and validate any user registration form with a custom rule.

May 20, 2022
Laravel package for giving admin-created accounts to users via 'set-password' email.

Invytr When making a website where users are created instead of registering themselves, you are faced with the challenge of safely giving users the ac

Mar 18, 2022
A bring-your-own-email-first newsletter service. ✨

Typewrite Typewrite a hosted bring-your-own-email newsletter service for people who need a simplistic and privacy-first newsletter service. The core a

Dec 2, 2021
Provides email verification on the go.

Email Checker Email Checker was created and maintained by Aman Nurani. It provides a powerful email validating system for both development and product

May 11, 2022
Laravel Email Audit Log

This service provider will monitor all emails that has been sent out of your system. Sent emails will be stored in email_audit_log table

Apr 13, 2022
LERN is a Laravel package that will record exceptions into a database and will notify you via Email, Pushover or Slack.

LERN is a Laravel package that will record exceptions into a database and will notify you via Email, Pushover or Slack.

Feb 13, 2022