Giter Club home page Giter Club logo

deep-email-validator's Introduction

Email Validator

Validates email addresses based on regex, common typos, disposable email blacklists, DNS records and SMTP server response.

  • Validates email looks like an email i.e. contains an "@" and a "." to the right of it.
  • Validates common typos e.g. [email protected] using mailcheck.
  • Validates email was not generated by disposable email service using disposable-email-domains.
  • Validates MX records are present on DNS.
  • Validates SMTP server is running.
  • Validates mailbox exists on SMTP server.
  • Native typescript support.

Getting Started

Compatible with nodejs only. Not browser ready.

Install like so

npm i deep-email-validator --save

or with yarn

yarn add deep-email-validator

Use like so

import { validate } from 'deep-email-validator'
const main = async () => {
  let res = await validate('[email protected]')
  // {
  //   "valid": false,
  //   "reason": "smtp",
  //   "validators": {
  //       "regex": {
  //         "valid": true
  //       },
  //       "typo": {
  //         "valid": true
  //       },
  //       "disposable": {
  //         "valid": true
  //       },
  //       "mx": {
  //         "valid": true
  //       },
  //       "smtp": {
  //         "valid": false,
  //         "reason": "Mailbox not found.",
  //       }
  //   }
  // }

  // Can also be called with these default options
  await validate({
    email: '[email protected]',
    sender: '[email protected]',
    validateRegex: true,
    validateMx: true,
    validateTypo: true,
    validateDisposable: true,
    validateSMTP: true,
  })
}

If you want to validate domains with TLDs that are not supported by default, you can use additionalTopLevelDomains option:

await validate({
  email: '[email protected]',
  sender: '[email protected]',
  validateRegex: true,
  validateMx: true,
  validateTypo: true,
  validateDisposable: true,
  validateSMTP: true,
  additionalTopLevelDomains: [ 'ir' ]
})

For a list of TLDs that are supported by default you can see here.

Default options can be found here

deep-email-validator's People

Contributors

dependabot[bot] avatar ialex97 avatar information-security avatar mfbx9da4 avatar micalevisk avatar mmagyar avatar tabbathacrouch avatar to7be avatar utob-ir avatar vlopp avatar zefir-git avatar zingerj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

deep-email-validator's Issues

Validation does not work properly with edu.pl domains and disposable emails

E-mail address from the @agh.edu.pl domain (correct university emails) is recognized as a typo with suggestion that it should be @agh.edu
Why does disposable, mx and smtp also not valid?

{
  valid: false,
  validators: {
    regex: { valid: true },
    typo: {
      valid: false,
      reason: 'Likely typo, suggested email: ***@agh.edu'
    },
    disposable: { valid: false },
    mx: { valid: false },
    smtp: { valid: false }
  },
  reason: 'typo'
}

I tried disposable emails from: https://temp-mail.org and https://mail.tm/ in both cases "disposable" was valid...

Real Regex for the regex option

const emailReg = new RegExp(
  /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
/**
 * Validate email function with regular expression
 *
 * If email isn't valid then return false
 *
 * @param email
 * @return Boolean
 */
export const validateEmail = (email: string): boolean => emailReg.test(email);

I use this function in several projects. I think it's more robust than the regex option here, but I need all your other options, so what do you think?

thanks

Use node v20 fetch instead of axios

Deep dependency vulnerability with Axios:

axios  0.8.1 - 1.5.1
Severity: moderate
Axios Cross-Site Request Forgery Vulnerability - https://github.com/advisories/GHSA-wf5p-g6vw-rhxx
No fix available
node_modules/axios
  deep-email-validator  *
  Depends on vulnerable versions of axios
  node_modules/deep-email-validator

Valid emails marked as typo

Valid emails marked as invalid some time e.g on [email protected]
I am getting

"result": {
            "valid": false,
            "validators": {
                "regex": {
                    "valid": true
                },
                "typo": {
                    "valid": false,
                    "reason": "Likely typo, suggested email: [email protected]"
                },
                "disposable": {
                    "valid": false
                },
                "mx": {
                    "valid": false
                },
                "smtp": {
                    "valid": false
                }
            },
            "reason": "typo"
        }

Multiple Failures reasons expected but not received

When a pass an email address [email protected] which has a bad MX record and is suggested as a Typo I only get a reason back in the typo validator when I expected a reason back in all failing validators.

Is this expected or a bug?

{
  valid: false,
  validators: {
    regex: { valid: true },
    typo: {
      valid: false,
      reason: 'Likely typo, suggested email: [email protected]'
    },
    disposable: { valid: false },
    mx: { valid: false },
    smtp: { valid: false }
  },
  reason: 'typo'
}

SMTP Timeout

Running my server locally is fine, but after running my express server online, smtp timeout, and it send validity as false

Deep email validator in the aws cloud shell / Lambda not working

I'm unable to run the deep email validator in the aws cloud shell / Lambda.

Please suggest.

Getting SMTP timeout / SMTP false.

Below is the code used.

const emailValidator = require('deep-email-validator');

// Get the email address from command-line arguments
const emailToValidate = process.argv[2];

async function validateEmail(email) {
try {
const { valid, reason, validators, address } = await emailValidator.validate(email);
console.log('validating smtp',validators?.smtp.valid)
if (valid) {
console.log(Email ${email} is valid and deliverable.);
// Proceed with sending the email
} else {
console.error(Email ${email} is not valid. Reason: ${reason});
// Handle the case where the email address is not valid
}
} catch (error) {
console.error(An error occurred while validating the email: ${error.message});
// Handle the error (e.g., log it or show an error message)
}
}

if (!emailToValidate) {
console.error('Usage: node validateEmail.js ');
process.exit(1);
}

validateEmail(emailToValidate);

This works completely fine in the local environment.
But fails in AWS Cloud Shell or AWS Lambda.

Please look into this issue.

SMTP Timeout for valid SMTP servers like Gmail.com, etc

Hi,

For every email even with valid SMTP server, its giving timeout error and returning valid:false for SMTP.

I tested with this personal email of mine [email protected]

and output is

{
  valid: false,
  validators: {
    regex: { valid: true },
    typo: { valid: true },
    disposable: { valid: true },
    mx: { valid: true },
    smtp: { valid: false, reason: 'Timeout' }
  },
  reason: 'smtp'
}

Error on smpt

While I was testing something, I discovered that there was a problem with Outlook / Hotmail addresses. Here's an example, the username of the email is random so as not to leak a private email.

import { validate } from 'deep-email-validator'
const main = async () => {
    let res = await validate({
        email: '[email protected]'
    })
    console.log(res)
}

main()

Response:

{
  valid: false,
  validators: {
    regex: { valid: true },
    typo: { valid: true },
    disposable: { valid: true },
    mx: { valid: true },
    smtp: { valid: false, reason: 'Mailbox not found.' }
  },
  reason: 'smtp'
}

The problem is directly in [****](smtp: { valid: false, reason: 'Mailbox not found.' })
The mailbox exists, but it is said here that it does not exist. I have been able to determine that with Outlook and Hotmail addresses so far that it is not displayed correctly.

SMTP always returns with a Timeout error

Hi,
The email validation always returns with a 'Timeout' reason, which turns the valid flag to false. I am running a MySql DB with a React frontend on Ubuntu 20.04 on NodeJs.

If SMTP is defaulted to False, then all email addresses though invalid are taken as valid.

Please advise.

Regex give me a positive when it should be negative

I have a user who could register in our database while his email is not a valid one : ĥ[email protected]

When I tested it, the regex said it's a valid one when it should not...

> await validate({ email: [email protected]", validateRegex: true, validateMx: true, validateTypo: true, validateDisposable: true, validateSMTP: false })

{
  valid: true,
  validators: {
    regex: { valid: true },
    typo: { valid: true },
    disposable: { valid: true },
    mx: { valid: true },
    smtp: { valid: true }
  }
}

HELO issues lead to IP Blacklisting

The library when used long term leads to a blacklist by https://check.spamhaus.org specifically for Outlook emails.

Replication Steps:

  • Enter any outlook business email
  • Library tries to connect with MX Exchange of outlook
  • HELO is sent as same as MX Exchange of outlook
  • Every time an email is validated a different HELO originates from the same IP which is a spam practice

The library should not encourage this behaviour and instead ask to define a HELO with best practices.

Production Server is not able to find api/emailVerifier

Hi ,
I have deployed my app (that is simple form to verify email in react) on digital ocean.
I am using nginx. iI have installed ur module on my server also.

My verifier works perfect on localhost.

My problem is when i enter email address and enter submit, i get 404 ERROR.

When i go to https://www.mydomain/api/emailVerifier. i get 404 not found,

this is code from my app.js

handleSubmit = async e => {
e.preventDefault();
const response = await fetch('/api/emailVerifier', {
method: 'POST',
// body: this.state,
headers: {
'Content-Type': 'application/json',
},

  body: JSON.stringify({ post: this.state.post }),

});
const body = await response.text();

this.setState({ responseToPost: body });

};

Thanks

Vulnerable version of axios is a dependency

Hello! npm audit shows that there is a high-severity vulnerability because of this pkg's dependepcy.

# npm audit report

axios  <0.21.1
Severity: high
Server-Side Request Forgery - https://npmjs.com/advisories/1594
No fix available
node_modules/deep-email-validator/node_modules/axios
  deep-email-validator  *
  Depends on vulnerable versions of axios
  node_modules/deep-email-validator

2 high severity vulnerabilities

Some issues need review, and may require choosing
a different dependency.

Suggesting to set up a newer version of axios as dependency (or add it as peerDependency?)

Module not found: DNS

I had this message when using the library

image

My code:

import validate from 'deep-email-validator';

  const onSubmit = async (event: FormEvent<Element>) => {
    event.preventDefault();

    const res = await validate(email);
    console.log({ res });
  };

this returns false for all email addresses

I tried to check some email addresses with this package but soon i recognized that every response is valid: false.
After i tried my own personal gmail address and another one (own domain) this validator returned smtp false in both.

RangeError: Maximum call stack size exceeded

Hello, first of all I'd like to thank you for such a cool library. I've been trying to use it for some project of mine and it worked really well most of the time, except for some invalid addresses which caused this issue:

Exception in PromiseRejectCallback:
internal/process/promises.js:94
function resolveError(type, promise, reason) {
                     ^

RangeError: Maximum call stack size exceeded
internal/errors.js:309
  err.stack;
      ^

RangeError: Maximum call stack size exceeded
    at addCodeToName (internal/errors.js:309:7)
    at new NodeError (internal/errors.js:270:7)
    at doWrite (_stream_writable.js:399:19)
    at writeOrBuffer (_stream_writable.js:387:5)
    at Socket.Writable.write (_stream_writable.js:318:11)
    at Socket.<anonymous> (/home/ialex/Projects/Node/deep-email-validator/dist/smtp/smtp.js:40:20)
    at Socket.emit (events.js:315:20)
    at Socket.EventEmitter.emit (domain.js:482:12)
    at Socket.<anonymous> (/home/ialex/Projects/Node/deep-email-validator/dist/smtp/smtp.js:31:20)
    at Socket.emit (events.js:315:20)

Upon further investigation, the issue occurred when the fail event of the socket was triggered by writing to an already closed socket. This caused the event to be triggered again due to this exception, all while trying to resolve the promise (possibly due to the error event being triggered by writing to a closed socket?).

Anyhow, I've opened PR #2 which adds some checks before writing to the socket and it seems the error goes away while returning an invalid address status:

{
  valid: false,
  validators: {
    regex: { valid: true },
    typo: { valid: true },
    disposable: { valid: true },
    mx: { valid: true },
    smtp: { valid: false, reason: 'Unrecognized SMTP response.' }
  },
  reason: 'smtp'
}

Error while hooking it with yup in React

Hi,
I am getting an error

deep_email_validator__WEBPACK_IMPORTED_MODULE_6___default.a.validate is not a function

while trying to hook deep-email-validator with React.

import emailValidator from 'deep-email-validator';

const isEmailValid = async (email) => {
  return emailValidator.validate(email);
};

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i;
const passwordRegex = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/g;
// const phoneRegex = /^([0]{1}|\+?[234]{3})([7-9]{1})([0|1]{1})([\d]{1})([\d]{7})$/g
const validationSchema = yup.object().shape({
  email: yup
    .string()
    .matches(emailRegex, 'Invalid email.')
    .test('working-email', 'Must be an working email', async (value) => {
      const res = await isEmailValid(value);
      return res.valid;
    })
    .required('Email is required.'),
  password: yup
    .string()
    .required('Password is required.')
    .matches(
      passwordRegex,
      'Password must be min 8 characters, have 1 special character[#?!@$%^&*-], 1 uppercase, 1 lowercase and 1 number.'
    ),
  confirmPassword: yup
    .string()
    .test('password-match', 'Passwords must match.', function (value) {
      return this.parent.password === value;
    }),
`});

Please look into it @mfbx9da4

Spaces are accepted before @ sign

Hi,

I noticed that spaces are accepted before the @ sign of the email address, values such as "jo [email protected]", "john. [email protected]" or "john.doe @example.com" are not flagged as invalid, here is an example of result obtained:

jo [email protected]:
{
  "valid": true,
  "validators": {
    "regex": {
      "valid": true
    },
    "typo": {
      "valid": true
    },
    "disposable": {
      "valid": true
    },
    "mx": {
      "valid": true
    },
    "smtp": {
      "valid": true
    }
  }
}

This test is done with the following code:

async function checkEmail( email: string ) {
  const valid = await validate({
    email: email,
    sender: email,
    validateRegex: true,
    validateMx: true,
    validateTypo: true,
    validateDisposable: true,
    validateSMTP: false,
  });
  logger.error( `${email}:\n${JSON.stringify( valid, null, 2)}` );
}

I would expect it to fail at the regexp stage. For sure an address with a space in that part is refused by email servers.

Let me known if you need any more details.
Denis

Support for additional second level domains and domains. gmrit.edu.in is a valid mail domain, but typo module suggesting gmx.com.

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/deep-email-validator/dist/index.js b/node_modules/deep-email-validator/dist/index.js
index d76e024..179994d 100644
--- a/node_modules/deep-email-validator/dist/index.js
+++ b/node_modules/deep-email-validator/dist/index.js
@@ -28,7 +28,7 @@ function validate(emailOrOptions) {
                 return output_1.createOutput('regex', regexResponse);
         }
         if (options.validateTypo) {
-            const typoResponse = yield typo_1.checkTypo(email, options.additionalTopLevelDomains);
+            const typoResponse = yield typo_1.checkTypo(email, options.additionalTopLevelDomains, options.additionalSLDs,options.additionalDomains);
             if (typoResponse)
                 return output_1.createOutput('typo', typoResponse);
         }
diff --git a/node_modules/deep-email-validator/dist/options/options.d.ts b/node_modules/deep-email-validator/dist/options/options.d.ts
index 3b2ace0..e4ef9f9 100644
--- a/node_modules/deep-email-validator/dist/options/options.d.ts
+++ b/node_modules/deep-email-validator/dist/options/options.d.ts
@@ -8,6 +8,8 @@ declare type Options = {
 };
 declare type MailCheckOptions = {
     additionalTopLevelDomains?: string[];
+    additionalSLDs?: string[],
+    additionalDomains?: string[]
 };
 export declare type ValidatorOptions = Partial<Options> & {
     email: string;
diff --git a/node_modules/deep-email-validator/dist/typo/typo.d.ts b/node_modules/deep-email-validator/dist/typo/typo.d.ts
index 3d376a8..ec1b3c4 100644
--- a/node_modules/deep-email-validator/dist/typo/typo.d.ts
+++ b/node_modules/deep-email-validator/dist/typo/typo.d.ts
@@ -1 +1 @@
-export declare const checkTypo: (email: string, additionalTLDs?: string[] | undefined) => Promise<string | undefined>;
+export declare const checkTypo: (email: string, additionalTLDs?: string[] | undefined,additionalSLDs?: string[] | undefined,additionalDomains?: string[] | undefined ) => Promise<string | undefined>;
diff --git a/node_modules/deep-email-validator/dist/typo/typo.js b/node_modules/deep-email-validator/dist/typo/typo.js
index 572f508..54940f8 100644
--- a/node_modules/deep-email-validator/dist/typo/typo.js
+++ b/node_modules/deep-email-validator/dist/typo/typo.js
@@ -14,15 +14,27 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
 Object.defineProperty(exports, "__

Do not support some domains, like .cn, .lv, .shop

Hi, I just checked some TLD, such like .cn, .site, .lv, .inc, .ltd, .shop. all these failed for the reason "typo"

const { validate } = require('deep-email-validator');

async function Validate(email) {
    const res = await validate({
        email: email,
        sender: '[email protected]',
        validateRegex: true,
        validateMx: false,
        validateTypo: true,
        validateDisposable: true,
        validateSMTP: false,
    });
    console.log(email, res.valid, res.valid ? '': res.reason);
}

const emails = [
    '[email protected]', 
    '[email protected]', 
    '[email protected]', 
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]'
];
emails.forEach(x => {
    Validate(x);
});

result as

No handling for close event in smtp validation

There's no event handler for the close event in the smtp validator. If you give it the email [email protected] it'll never resolve its promise and your script will exit without an error.

There should be a block like this:

    socket.on("close", (err)=>{
      //resolve the promise with something
    })

in src/smtp/smtp.ts

Support SMTPS

wikipedia.org/wiki/SMTPS

  • Port 587 → STARTTLS
  • Port 465 → TLS

Might fix #7, generally this library has been wrongly reporting invalid mailbox for a lot of domains that don't offer plain SMTP for me

Update library with new disposable mail providers

➡️I just checked this library with a disposable email. The library shows it's a valid one.
email: [email protected]

➡️I typed some chars randomly and it was valid.
email: [email protected]

{
        "valid": true,
        "validators": {
            "regex": {
                "valid": true
            },
            "typo": {
                "valid": true
            },
            "disposable": {
                "valid": true
            },
            "mx": {
                "valid": true
            },
            "smtp": {
                "valid": true
            }
        }
    }

➡️ An email from govt. website shows email is invalid. email: [email protected].
while this website shows it's a valid one.

{
        "valid": false,
        "validators": {
            "regex": {
                "valid": true
            },
            "typo": {
                "valid": false,
                "reason": "Likely typo, suggested email: [email protected]"
            },
            "disposable": {
                "valid": false
            },
            "mx": {
                "valid": false
            },
            "smtp": {
                "valid": false
            }
        },
        "reason": "typo"
    }

RangeError: Maximum call stack size exceeded

0|server | function promiseRejectHandler(type, promise, reason) {
0|server | ^
0|server |
0|server | RangeError: Maximum call stack size exceeded
0|server | RangeError: Maximum call stack size exceeded
0|server | at formatWithOptions (internal/util/inspect.js:1876:27)
0|server | at format (internal/util/inspect.js:1819:10)
0|server | at getMessage (internal/errors.js:367:43)
0|server | at new NodeError (internal/errors.js:263:23)
0|server | at doWrite (_stream_writable.js:399:19)
0|server | at writeOrBuffer (_stream_writable.js:387:5)
0|server | at Socket.Writable.write (_stream_writable.js:318:11)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.