Skip to content

Add promise support #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,35 @@
language: node_js
node_js:
- "0.10"
- "22.x"
- "lts/*"
- "node"

os:
- linux
- windows
- osx

branches:
only:
- main
- master

cache:
directories:
- node_modules

before_install:
- npm i -g npm
# Workaround for a permissions issue with Travis virtual machine images
- npm install -g npm@latest

script:
- npm test
- npm run lint
- npm test
- npm run test:coverage

after_success:
- npm run coverage

notifications:
email: false
webhooks: false

267 changes: 186 additions & 81 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,81 +1,186 @@
mailgun-validate-email
=================

Super tiny wrapper of email validation API from [Mailgun](http://www.mailgun.com/),
useful in form validation. This can be most useful in form validation to avoid those pesky spam emails.

### Disclaimer
This module uses a third party service from Mailgun to verify the validity of the email,
you can read all the info in their [API docs](http://documentation.mailgun.com/api-email-validation.html)
Emails are *securely transmitted* using Public Key Cryptography

# Badgers
[![NPM](https://nodei.co/npm/mailgun-validate-email.png?downloads=true&stars=true)](https://nodei.co/npm/mailgun-validate-email/)

[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/diasdavid/mailgun-validate-email?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![Dependency Status](https://david-dm.org/diasdavid/mailgun-validate-email.svg)](https://david-dm.org/diasdavid/mailgun-validate-email)
[![Build Status](https://travis-ci.org/diasdavid/mailgun-validate-email.svg)](https://travis-ci.org/diasdavid/mailgun-validate-email)

## Usage

```sh
npm install mailgun-validate-email --save
```

```javascript
var validator = require('mailgun-validate-email')('INSERT-YOUR-MAILGUN-PUBKEY-HERE')
validator("[email protected]", function (err, result){
if(err) {
// email was not valid
} else {
console.log(result);
// register the person for your service etc.
}
})
```

Output will be something like

```javascript
{
is_valid: true,
parts: {
local_part: banana,
domain: papaia.com,
display_name: null
},
address: '[email protected]',
did_you_mean: null
}
```


### *Why* use Third-Party Email Validation?

There are *easier* ways of checking if an email conforms to the correct *format*
e.g: using [**Joi**](https://github.com/hapijs/joi#example) `Joi.string().email()`
But a validation library only checks that the address "*looks*" valid,
the Mailgun API actually checks if the domain has a valid [**DNS mx record**](http://en.wikipedia.org/wiki/MX_record)
(checking if the domain *accepts* emails).

This means you don't waste time (or money) sending emails to **[email protected]**
(*valid* email address which will *fail* to deliver and thus
clog up your inbox with failure reports!)

**Note**: this will *not* prevent people from registering with your
service/app using a *real* email they *don't control*.
e.g: **[email protected]** ...
so you should still get people to *confirm* their email address by sending them
an email with a unique token.
(this will prevent people registering as someone else)


## License

(The MIT License)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# mailgun-validate-email-esm

[![Node.js Version](https://img.shields.io/badge/node-%3E%3D22.0.0-brightgreen.svg)](https://nodejs.org/)
[![github version](https://badge.fury.io/gh/dan-willett%2Fmailgun-validate-email.svg)](https://badge.fury.io/gh/dan-willett%2Fmailgun-validate-email)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A modern, lightweight wrapper for the Mailgun v4 Inbox Ready API. This module helps you validate email addresses in real-time, check deliverability, and prevent fake or invalid email submissions.

## Features

- **Mailgun v4 Inbox Ready API** - Uses the latest validation endpoints
- **Provider Lookup** - Optional provider verification for accurate results
- **Flexible Integration** - Supports both Promise and callback patterns
- **Modern JavaScript** - Built with ES Modules and async/await
- **Comprehensive Error Handling** - Detailed error messages and status codes
- **TypeScript Support** - Includes TypeScript type definitions
- **Node.js 22+** - Optimized for modern Node.js versions

## Installation

```sh
npm install mailgun-validate-email-esm
# or
yarn add mailgun-validate-email-esm
```

## Usage

### ES Modules (Recommended)

```javascript
import createValidator from 'mailgun-validate-email-esm';

// Create validator instance with your Mailgun public API key
const validate = createValidator('your-mailgun-public-key');

// Using async/await (recommended)
try {
const result = await validate('[email protected]');
console.log('Validation result:', result);
} catch (error) {
console.error('Validation failed:', error);
}

// Or with Promise
validate('[email protected]')
.then(result => console.log('Valid:', result.is_valid))
.catch(error => console.error('Error:', error));

// Or with callback
validate('[email protected]', (error, result) => {
if (error) {
console.error('Validation error:', error);
return;
}
console.log('Is valid?', result.is_valid);
});
```

### Response Format

The validation result includes the following fields:

```javascript
{
"address": "[email protected]",
"is_valid": true, // Backward compatibility field
"result": "deliverable", // 'deliverable', 'undeliverable', 'do_not_send', 'catch_all', 'unknown'
"risk": "low", // 'high', 'medium', 'low', 'unknown'
"is_disposable_address": false,
"is_role_address": false,
"reason": [], // Array of reasons if validation failed
"suggestion": null, // Suggested correction if available
"mailbox_verification": "true" // If mailbox verification was performed
}
```

### Configuration Options

```javascript
import createValidator from 'mailgun-validate-email-esm';

const validate = createValidator('your-api-key', {
providerLookup: true, // Enable/disable provider lookup (default: true)
timeout: 10000 // Request timeout in milliseconds (default: 10000)
});
```

### Error Handling

The module throws/rejects with detailed error objects that include:
- `message`: Human-readable error message
- `code`: Error code:
- `EAUTH`: Authentication failed (401)
- `EAPI`: API error (4xx/5xx)
- `ETIMEDOUT`: Request timed out
- `EUNKNOWN`: Unknown error
- `status`: HTTP status code (for API errors)

Example error handling:

```javascript
try {
await validate('[email protected]');
} catch (error) {
if (error.code === 'EAUTH') {
console.error('Authentication failed. Please check your API key.');
} else if (error.code === 'ETIMEDOUT') {
console.error('Request timed out. Please try again later.');
} else {
console.error('Validation failed:', error.message);
}
}
```


## Why Use Mailgun's Email Validation?

While there are simpler ways to check if an email is formatted correctly (like using `Joi.string().email()`), Mailgun's validation goes much further:

- **MX Record Validation**: Verifies the domain has valid MX records
- **Disposable Email Detection**: Identifies temporary/throwaway email addresses
- **Role-based Email Detection**: Flags emails like `admin@` or `support@`
- **Mailbox Verification**: Checks if the mailbox can receive emails
- **Typo Detection**: Suggests corrections for common typos

### Example Validation Scenarios

```javascript
// Valid email with common typo
const result = await validate('[email protected]');
// result.did_you_mean might be '[email protected]'

// Disposable email address
const disposable = await validate('[email protected]');
// disposable.is_disposable_address === true

// Non-existent domain
const invalid = await validate('[email protected]');
// invalid.is_valid === false
// invalid.reason === 'no_mx_record'
```

### Important Notes

- This service requires a valid Mailgun account and API key
- Always implement proper error handling in your application
- Consider implementing rate limiting to prevent abuse
- For production use, you may want to implement caching of validation results
- Remember to handle timeouts and network issues gracefully

### Security Considerations

- Never expose your private Mailgun API key in client-side code
- Consider implementing server-side validation as an API endpoint
- Be aware of rate limits on the Mailgun API
- Always validate and sanitize all user input


## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

MIT License

Copyright (c) 2024 Dan Willett

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
44 changes: 21 additions & 23 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
{
"name": "mailgun-validate-email",
"version": "2.0.3",
"description": "validate email addresses with mailgun API",
"main": "src/index.js",
"name": "mailgun-validate-email-esm",
"version": "4.0.2",
"description": "Validate email addresses using Mailgun API",
"type": "module",
"exports": "./src/index.js",
"engines": {
"node": ">=22.0.0"
},
"publishConfig": {
"access": "public"
},
"scripts": {
"lint": "standard",
"test": "node ./node_modules/.bin/lab -r tap tests/*-test.js | ./node_modules/.bin/tap-spec",
"test-cov": "node ./node_modules/.bin/lab -t 88 tests/*-test.js",
"test-cov-html": "node ./node_modules/.bin/lab -r html -o coverage.html tests/*-test.js"
"test": "node --test",
"lint": "eslint .",
"test:coverage": "c8 node --test"
},
"pre-commit": [
"lint",
"test",
"test-cov"
],
"repository": {
"type": "git",
"url": "https://github.com/diasdavid/mailgun-validate-email"
"url": "https://github.com/dan-willett/mailgun-validate-email"
},
"keywords": [
"mailgun",
Expand All @@ -27,20 +28,17 @@
"scam",
"valid"
],
"author": "David Dias",
"author": "Dan Willett",
"license": "MIT",
"bugs": {
"url": "https://github.com/diasdavid/mailgun-validate-email"
"url": "https://github.com/dan-willett/mailgun-validate-email/issues"
},
"dependencies": {
"request": "^2.25.0"
"node-fetch": "^3.3.2"
},
"devDependencies": {
"code": "^1.2.1",
"jscs": "^1.7.3",
"jshint": "^2.5.10",
"lab": "^5.0.3",
"pre-commit": "^1.1.2",
"tap-spec": "^2.1.0"
"c8": "^9.1.0",
"eslint": "^8.56.0",
"eslint-config-standard": "^17.1.0"
}
}
Loading