validmail 1.0.0-test → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +534 -4
- package/dist/index.cjs +91 -0
- package/dist/index.d.cts +237 -0
- package/dist/index.d.ts +237 -0
- package/dist/index.js +90 -0
- package/package.json +56 -7
- package/index.d.ts +0 -2
- package/index.js +0 -8
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this package are documented here. This project follows [Semantic Versioning](https://semver.org/).
|
|
4
|
+
|
|
5
|
+
## 1.0.0 - Unreleased
|
|
6
|
+
|
|
7
|
+
First release.
|
|
8
|
+
|
|
9
|
+
- `validmail(email, options?)` validates an address for server-side signups and resolves with `{ valid, reason, message, email, local, domain, asciiDomain, checks, mxRecords }`. Never rejects for bad input.
|
|
10
|
+
- Syntax check (RFC 5321/5322, practical subset): 64/254/63 length limits in octets, dot rules, `allowQuoted`, `allowIpLiteral` (IPv4 and `IPv6:`), `allowUnicodeLocal` (RFC 6531), `requireTld`. Unicode domains are converted to punycode with `domainToASCII` for DNS. Linear time, no backtracking regular expressions.
|
|
11
|
+
- Disposable domain check with ~590 built-in domains, subdomain-aware, plus `blockDomains` and `allowDomains`.
|
|
12
|
+
- Role accounts (`admin@`, `support@`, `noreply@`, ...) flagged in `checks.role`, rejected with `rejectRole`.
|
|
13
|
+
- MX check via `node:dns/promises`: A/AAAA fallback (implicit MX, RFC 5321 §5.1, `implicitMx`), null MX detection (RFC 7505), DNS errors reported as `status: 'error'` separately from definite failures, `allowDnsErrors`, `timeout`, `AbortSignal`.
|
|
14
|
+
- Injectable `resolver` for tests and custom DNS servers.
|
|
15
|
+
- In-memory domain cache with TTL (`cache: true | false | Map`, `cacheTtl`), bounded to 10,000 domains; concurrent lookups of the same domain share one query.
|
|
16
|
+
- `validateSync` / `validmail.sync`, `validateMany` with `concurrency`, `checkSyntax`, `checkMx`, `isValidEmail`, `isValidEmailAsync`, `isDisposable`, `isRoleAccount`, `disposableDomains`, `clearCache`.
|
|
17
|
+
- No SMTP probing, by design.
|
|
18
|
+
- ESM + CommonJS, TypeScript types with a result that narrows on `valid`, zero dependencies.
|
package/README.md
CHANGED
|
@@ -1,18 +1,548 @@
|
|
|
1
1
|
# validmail
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Check email addresses on the server: syntax, disposable domains and MX (DNS) records.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
[](https://www.npmjs.com/package/validmail) [](https://bundlephobia.com/package/validmail) [](LICENSE)
|
|
6
|
+
|
|
7
|
+
validmail checks an email address before you save it, for example in a sign-up handler. It checks the format, blocks throwaway (disposable) email services, and asks DNS whether the domain can receive email. The result tells you which check failed and why. It runs in Node.js, Bun and Deno.
|
|
8
|
+
|
|
9
|
+
> **Validating in the browser?** Use [inboxok](https://www.npmjs.com/package/inboxok). It runs syntax, disposable and typo checks in forms, synchronously and without DNS. Use inboxok while the user types, and validmail on the server when the form is submitted.
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- **Syntax check** that follows RFC 5321/5322 length limits (64/254/63) and dot rules.
|
|
14
|
+
- **Unicode domains** (`bücher.de`) converted to punycode, the ASCII form that DNS uses.
|
|
15
|
+
- **MX check** with A/AAAA fallback and **null MX** detection (a domain that says "no email here").
|
|
16
|
+
- **"No mail server" and "DNS timed out" are different results**, so a slow DNS server does not turn away real users.
|
|
17
|
+
- **~590 disposable domains** built in, subdomains included, plus your own block and allow lists.
|
|
18
|
+
- **Role accounts** (`admin@`, `support@`, `noreply@`) flagged, or rejected with `rejectRole`.
|
|
19
|
+
- **Built for servers**: timeouts, `AbortSignal`, a DNS cache, and `validateMany` with a concurrency limit.
|
|
20
|
+
- **Easy to test**: pass a fake DNS resolver, no network needed.
|
|
21
|
+
- **No SMTP probing**, no ReDoS (regular expressions that hang on bad input), zero dependencies, ~8 KB gzipped.
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
6
24
|
|
|
7
25
|
```sh
|
|
8
26
|
npm install validmail
|
|
9
27
|
```
|
|
10
28
|
|
|
29
|
+
```sh
|
|
30
|
+
pnpm add validmail
|
|
31
|
+
yarn add validmail
|
|
32
|
+
bun add validmail
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Quick start
|
|
36
|
+
|
|
11
37
|
```js
|
|
12
|
-
|
|
13
|
-
|
|
38
|
+
import validmail from 'validmail'
|
|
39
|
+
|
|
40
|
+
const result = await validmail('Jane.Doe@Gmail.COM')
|
|
41
|
+
result.valid // => true
|
|
42
|
+
result.email // => 'Jane.Doe@gmail.com' (domain lowercased)
|
|
43
|
+
result.mxRecords // => [{ exchange: 'gmail-smtp-in.l.google.com', priority: 5 }, ...]
|
|
44
|
+
|
|
45
|
+
await validmail('someone@mailinator.com') // => { valid: false, reason: 'disposable', ... }
|
|
46
|
+
await validmail('someone@gmial.con') // => { valid: false, reason: 'domain_not_found', ... }
|
|
47
|
+
await validmail('someone@example.com') // => { valid: false, reason: 'null_mx', ... }
|
|
48
|
+
await validmail('john..doe@example.com') // => { valid: false, reason: 'local_dot', ... }
|
|
49
|
+
|
|
50
|
+
// Same checks without DNS, synchronous:
|
|
51
|
+
validmail.sync('someone@mailinator.com') // => { valid: false, reason: 'disposable', ... }
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
CommonJS works too: `const validmail = require('validmail')`.
|
|
55
|
+
|
|
56
|
+
## Table of contents
|
|
57
|
+
|
|
58
|
+
- [Usage](#usage)
|
|
59
|
+
- [Understand the checks](#understand-the-checks)
|
|
60
|
+
- [Validate a sign-up on the server](#validate-a-sign-up-on-the-server)
|
|
61
|
+
- [Check only the syntax (no DNS)](#check-only-the-syntax-no-dns)
|
|
62
|
+
- [Validate a list of emails](#validate-a-list-of-emails)
|
|
63
|
+
- [Block or allow more domains](#block-or-allow-more-domains)
|
|
64
|
+
- [Reject role accounts](#reject-role-accounts)
|
|
65
|
+
- [Use your own DNS servers](#use-your-own-dns-servers)
|
|
66
|
+
- [Use a fake DNS resolver in tests](#use-a-fake-dns-resolver-in-tests)
|
|
67
|
+
- [Cache DNS results](#cache-dns-results)
|
|
68
|
+
- [Set a timeout or cancel a check](#set-a-timeout-or-cancel-a-check)
|
|
69
|
+
- [Read the result](#read-the-result)
|
|
70
|
+
- [API](#api)
|
|
71
|
+
- [Comparison](#comparison)
|
|
72
|
+
- [Notes and limitations](#notes-and-limitations)
|
|
73
|
+
- [Requirements](#requirements)
|
|
74
|
+
- [License](#license)
|
|
75
|
+
|
|
76
|
+
## Usage
|
|
77
|
+
|
|
78
|
+
### Understand the checks
|
|
79
|
+
|
|
80
|
+
validmail runs four checks, in this order:
|
|
81
|
+
|
|
82
|
+
1. **Syntax**: is the address well-formed?
|
|
83
|
+
2. **Disposable**: is the domain a throwaway email service, or on your block list?
|
|
84
|
+
3. **Role**: is it a shared mailbox like `admin@` or `support@`? (Flagged only, unless you set `rejectRole`.)
|
|
85
|
+
4. **MX**: can the domain receive email?
|
|
86
|
+
|
|
87
|
+
If the syntax check fails, the other checks are skipped. DNS is only asked when all checks before it passed.
|
|
88
|
+
|
|
89
|
+
**What is MX?** MX (mail exchanger) records tell the internet which server receives email for a domain. If a domain has no MX records, it usually cannot receive email. Two details:
|
|
90
|
+
|
|
91
|
+
- A domain with no MX records but with an address (an A or AAAA record) is accepted. The email standard (RFC 5321 §5.1) says mail then goes to that address. This is called **implicit MX**. Set `implicitMx: false` to require real MX records.
|
|
92
|
+
- A domain can publish a **null MX** record (RFC 7505) to say "we never accept email". `example.com` does this. validmail rejects these addresses with `reason: 'null_mx'`.
|
|
93
|
+
|
|
94
|
+
### Validate a sign-up on the server
|
|
95
|
+
|
|
96
|
+
An Express route. Other frameworks work the same way.
|
|
97
|
+
|
|
98
|
+
```js
|
|
99
|
+
import express from 'express'
|
|
100
|
+
import validmail from 'validmail'
|
|
101
|
+
|
|
102
|
+
const app = express()
|
|
103
|
+
app.use(express.json())
|
|
104
|
+
|
|
105
|
+
app.post('/signup', async (req, res) => {
|
|
106
|
+
const check = await validmail(req.body.email, { timeout: 3000, allowDnsErrors: true })
|
|
107
|
+
if (!check.valid) {
|
|
108
|
+
return res.status(422).json({ error: check.message, reason: check.reason })
|
|
109
|
+
}
|
|
110
|
+
await createUser({ email: check.email }) // save the normalized address
|
|
111
|
+
await sendConfirmationEmail(check.email) // the only real proof that the mailbox exists
|
|
112
|
+
res.status(201).json({ ok: true })
|
|
113
|
+
})
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
- `allowDnsErrors: true` stops a DNS problem from turning away a real user. Definite failures (no such domain, no mail server, null MX) are still rejected.
|
|
117
|
+
- You do not need to check the input type first. A missing or non-string `email` gives `reason: 'invalid_type'`.
|
|
118
|
+
- `check.message` is a readable sentence, for example `"mailinator.com" is a disposable email service.`
|
|
119
|
+
|
|
120
|
+
### Check only the syntax (no DNS)
|
|
121
|
+
|
|
122
|
+
`validateSync` runs the syntax, disposable and role checks without DNS. `checkSyntax` runs only the syntax check. Both are synchronous and fast.
|
|
123
|
+
|
|
124
|
+
```js
|
|
125
|
+
import { validateSync, checkSyntax, isValidEmail } from 'validmail'
|
|
126
|
+
|
|
127
|
+
validateSync('someone@mailinator.com').reason // => 'disposable'
|
|
128
|
+
isValidEmail('jane@example.com') // => true (no DNS, so null MX is not checked)
|
|
129
|
+
isValidEmail('jane doe@example.com') // => false
|
|
130
|
+
|
|
131
|
+
const parts = checkSyntax('Jane@Bücher.DE')
|
|
132
|
+
parts.domain // => 'bücher.de'
|
|
133
|
+
parts.asciiDomain // => 'xn--bcher-kva.de'
|
|
134
|
+
|
|
135
|
+
checkSyntax('user@localhost').reason // => 'domain_no_tld'
|
|
136
|
+
checkSyntax('user@localhost', { requireTld: false }).valid // => true
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Without DNS you cannot know if the domain receives email. Run `validmail()` on the server before you save the address.
|
|
140
|
+
|
|
141
|
+
### Validate a list of emails
|
|
142
|
+
|
|
143
|
+
`validateMany` checks many addresses with a limit on how many run at the same time. Results come back in input order. Addresses on the same domain share one DNS lookup.
|
|
144
|
+
|
|
145
|
+
```js
|
|
146
|
+
import { validateMany } from 'validmail'
|
|
147
|
+
|
|
148
|
+
const emails = ['ann@gmail.com', 'bob@mailinator.com', 'carl@gmial.con']
|
|
149
|
+
const results = await validateMany(emails, { concurrency: 20, timeout: 3000 })
|
|
150
|
+
|
|
151
|
+
results.map((r) => r.valid) // => [true, false, false]
|
|
152
|
+
results.filter((r) => !r.valid).map((r) => `${r.email}: ${r.reason}`)
|
|
153
|
+
// => ['bob@mailinator.com: disposable', 'carl@gmial.con: domain_not_found']
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Block or allow more domains
|
|
157
|
+
|
|
158
|
+
```js
|
|
159
|
+
import { validateSync } from 'validmail'
|
|
160
|
+
|
|
161
|
+
const options = {
|
|
162
|
+
blockDomains: ['competitor.com', '@spam.example'], // extra domains to reject
|
|
163
|
+
allowDomains: ['mailinator.com'], // exempt from the built-in disposable list
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
validateSync('ann@mail.competitor.com', options).reason // => 'blocked'
|
|
167
|
+
validateSync('qa@mailinator.com', options).valid // => true
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
- Both lists include subdomains. A leading `@` or `.` is ignored, and Unicode domains are fine.
|
|
171
|
+
- `blockDomains` always wins over `allowDomains`, and it applies even with `disposable: false`.
|
|
172
|
+
- `disposable: false` turns off the built-in list. Disposable domains are then only flagged in `checks.disposable.isDisposable`.
|
|
173
|
+
|
|
174
|
+
Need a bigger disposable list? Pass the list from [mailchecker](https://www.npmjs.com/package/mailchecker) as `blockDomains`. validmail prepares each list object once and then reuses it:
|
|
175
|
+
|
|
176
|
+
```js
|
|
177
|
+
import mailchecker from 'mailchecker'
|
|
178
|
+
|
|
179
|
+
const blockDomains = mailchecker.blacklist() // Set of ~56,000 domains
|
|
180
|
+
await validmail(email, { blockDomains })
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Reject role accounts
|
|
184
|
+
|
|
185
|
+
Role accounts are shared mailboxes such as `admin@`, `info@`, `support@` and `noreply@`. By default they pass and are only flagged. Case and `+tags` are ignored.
|
|
186
|
+
|
|
187
|
+
```js
|
|
188
|
+
import { validateSync } from 'validmail'
|
|
189
|
+
|
|
190
|
+
validateSync('Support+billing@acme.com').checks.role
|
|
191
|
+
// => { status: 'pass', isRole: true, role: 'support' }
|
|
192
|
+
|
|
193
|
+
validateSync('support@acme.com', { rejectRole: true }).reason // => 'role'
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### Use your own DNS servers
|
|
197
|
+
|
|
198
|
+
Pass any `resolver` object with a `resolveMx` method. Node's `dns.promises.Resolver` lets you pick the DNS servers and their own timeout and retry settings.
|
|
199
|
+
|
|
200
|
+
```js
|
|
201
|
+
import { promises as dns } from 'node:dns'
|
|
202
|
+
import validmail from 'validmail'
|
|
203
|
+
|
|
204
|
+
const resolver = new dns.Resolver({ timeout: 2000, tries: 2 })
|
|
205
|
+
resolver.setServers(['1.1.1.1', '8.8.8.8'])
|
|
206
|
+
|
|
207
|
+
await validmail('ann@gmail.com', { resolver }) // => { valid: true, ... }
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
Each resolver object gets its own built-in cache. Create the resolver once and reuse it.
|
|
211
|
+
|
|
212
|
+
### Use a fake DNS resolver in tests
|
|
213
|
+
|
|
214
|
+
A plain object works as a resolver, so your tests need no network.
|
|
215
|
+
|
|
216
|
+
```js
|
|
217
|
+
import validmail from 'validmail'
|
|
218
|
+
|
|
219
|
+
const resolver = {
|
|
220
|
+
async resolveMx(host) {
|
|
221
|
+
if (host === 'example.com') return [{ exchange: 'mx.example.com', priority: 10 }]
|
|
222
|
+
throw Object.assign(new Error('not found'), { code: 'ENOTFOUND' })
|
|
223
|
+
},
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const found = await validmail('a@example.com', { resolver })
|
|
227
|
+
found.valid // => true
|
|
228
|
+
|
|
229
|
+
const missing = await validmail('a@unknown.test', { resolver })
|
|
230
|
+
missing.reason // => 'domain_not_found'
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Throw errors with Node's DNS error codes in `error.code`:
|
|
234
|
+
|
|
235
|
+
- `ENOTFOUND`: the domain does not exist.
|
|
236
|
+
- `ENODATA`: the domain exists but has no records of that type.
|
|
237
|
+
- Any other code: a DNS failure (`status: 'error'`, `reason: 'dns_error'`). `ETIMEOUT` gives `reason: 'timeout'`.
|
|
238
|
+
|
|
239
|
+
`resolve4` and `resolve6` are optional. They are used for the implicit MX fallback.
|
|
240
|
+
|
|
241
|
+
### Cache DNS results
|
|
242
|
+
|
|
243
|
+
The built-in cache is on by default:
|
|
244
|
+
|
|
245
|
+
- It keeps each domain's result for 1 hour (`cacheTtl`, in milliseconds).
|
|
246
|
+
- It holds at most 10,000 domains. The oldest entries are removed first.
|
|
247
|
+
- It stores only definite answers (pass or fail), never timeouts or DNS errors.
|
|
248
|
+
- When many checks for the same domain run at the same time, they share one DNS query.
|
|
249
|
+
|
|
250
|
+
```js
|
|
251
|
+
import validmail, { clearCache } from 'validmail'
|
|
252
|
+
|
|
253
|
+
const cache = new Map() // your own cache, which you can inspect or share
|
|
254
|
+
await validmail('ann@gmail.com', { cache, cacheTtl: 10 * 60_000 }) // keep for 10 minutes
|
|
255
|
+
const second = await validmail('bob@gmail.com', { cache })
|
|
256
|
+
|
|
257
|
+
second.checks.mx.cached // => true
|
|
258
|
+
cache.size // => 1 (one domain)
|
|
259
|
+
|
|
260
|
+
await validmail('ann@gmail.com', { cache: false }) // always asks DNS
|
|
261
|
+
clearCache() // empties the built-in cache; a Map you passed in is yours to clear
|
|
14
262
|
```
|
|
15
263
|
|
|
264
|
+
### Set a timeout or cancel a check
|
|
265
|
+
|
|
266
|
+
`timeout` (default `5000` ms) limits the whole DNS check, including the A/AAAA fallback. A slow answer becomes a result, not an exception:
|
|
267
|
+
|
|
268
|
+
```js
|
|
269
|
+
const result = await validmail(email, { timeout: 2000 })
|
|
270
|
+
|
|
271
|
+
result.checks.mx.status // => 'error' (when DNS was too slow)
|
|
272
|
+
result.reason // => 'timeout' ('dns_error' when DNS failed)
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
`status: 'error'` means "the check could not finish", not "this address is bad". Use `allowDnsErrors: true` to accept these addresses. `checks.mx.status` stays `'error'`, so you can log them or check again later.
|
|
276
|
+
|
|
277
|
+
To cancel a check, pass an `AbortSignal`. Unlike `timeout`, an abort **rejects** the promise with `signal.reason`:
|
|
278
|
+
|
|
279
|
+
```js
|
|
280
|
+
try {
|
|
281
|
+
await validmail(email, { signal: AbortSignal.timeout(1000) })
|
|
282
|
+
} catch (err) {
|
|
283
|
+
err.name // => 'TimeoutError'
|
|
284
|
+
}
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### Read the result
|
|
288
|
+
|
|
289
|
+
`validmail()`, `validateSync()` and `validateMany()` return the same result object. This is the result for `jane@example.com`:
|
|
290
|
+
|
|
291
|
+
```js
|
|
292
|
+
{
|
|
293
|
+
valid: false,
|
|
294
|
+
reason: 'null_mx', // reason of the first check that failed (undefined when valid)
|
|
295
|
+
message: 'The domain "example.com" does not accept email (null MX record, RFC 7505).',
|
|
296
|
+
email: 'jane@example.com', // normalized: trimmed, domain lowercased
|
|
297
|
+
local: 'jane', // the part before "@", case kept
|
|
298
|
+
domain: 'example.com', // Unicode form for Unicode domains ('bücher.de')
|
|
299
|
+
asciiDomain: 'example.com', // punycode form used for DNS ('xn--bcher-kva.de')
|
|
300
|
+
quoted: false, // the local part is quoted ("john doe"@...)
|
|
301
|
+
ipLiteral: false, // the domain is an IP address (user@[192.0.2.1])
|
|
302
|
+
checks: {
|
|
303
|
+
syntax: { status: 'pass' },
|
|
304
|
+
disposable: { status: 'pass', isDisposable: false },
|
|
305
|
+
role: { status: 'pass', isRole: false },
|
|
306
|
+
mx: { status: 'fail', reason: 'null_mx', message: '...' },
|
|
307
|
+
},
|
|
308
|
+
// mxRecords: [...] // sorted MX records, only when the MX check passed
|
|
309
|
+
}
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
Each check has a `status`:
|
|
313
|
+
|
|
314
|
+
| `status` | Meaning |
|
|
315
|
+
|---|---|
|
|
316
|
+
| `'pass'` | The check passed. |
|
|
317
|
+
| `'fail'` | The check failed. The address is invalid. |
|
|
318
|
+
| `'error'` | MX only. DNS timed out or failed (for example SERVFAIL or no network). The address might be fine. It counts as invalid unless `allowDnsErrors: true`. |
|
|
319
|
+
| `'skip'` | The check did not run: it is turned off, the domain is an IP address, or an earlier check failed. |
|
|
320
|
+
|
|
321
|
+
Extra fields: `checks.disposable` has `match` (the list entry that matched) and `source` (`'builtin'`, `'blockDomains'` or `'allowDomains'`). `checks.role` has `role` (for example `'support'`). `checks.mx` has `records`, `implicit` (implicit MX was used), `cached` and `code` (the DNS error code).
|
|
322
|
+
|
|
323
|
+
In TypeScript, checking `valid` narrows the type: when `valid` is `false`, `reason` and `message` are always set.
|
|
324
|
+
|
|
325
|
+
#### Reason codes
|
|
326
|
+
|
|
327
|
+
| Check | `reason` | Meaning |
|
|
328
|
+
|---|---|---|
|
|
329
|
+
| syntax | `invalid_type` | The input is not a string. |
|
|
330
|
+
| | `empty` | The input is empty or only spaces. |
|
|
331
|
+
| | `too_long` | More than 254 characters (counted in bytes, with the domain in punycode). |
|
|
332
|
+
| | `missing_at` | There is no `@`. |
|
|
333
|
+
| | `local_empty` | Nothing before the `@`. |
|
|
334
|
+
| | `local_too_long` | The part before the `@` is longer than 64 bytes. |
|
|
335
|
+
| | `local_invalid_char` | The part before the `@` has a character that is not allowed (space, `@`, `(`, `<`, control characters, ...). The message names it. |
|
|
336
|
+
| | `local_unicode` | The part before the `@` has non-ASCII characters, and `allowUnicodeLocal` is off. |
|
|
337
|
+
| | `local_dot` | The part before the `@` starts or ends with a dot, or has two dots in a row. |
|
|
338
|
+
| | `quoted_not_allowed` | A quoted local part (`"john doe"@...`), and `allowQuoted` is off. |
|
|
339
|
+
| | `quoted_invalid` | A quoted local part that is malformed. |
|
|
340
|
+
| | `domain_empty` | Nothing after the `@`. |
|
|
341
|
+
| | `domain_too_long` | The domain is longer than 253 characters. |
|
|
342
|
+
| | `domain_label_too_long` | One part of the domain (between dots) is longer than 63 characters. |
|
|
343
|
+
| | `domain_invalid` | Not a valid host name: characters other than letters, digits and hyphens, a part that starts or ends with `-`, an empty part (`a..com`, trailing dot), or bad punycode. |
|
|
344
|
+
| | `domain_no_tld` | No dot in the domain (`user@localhost`), and `requireTld` is on. |
|
|
345
|
+
| | `tld_invalid` | The top-level domain is a number (`user@1.2.3.4`) or one letter. |
|
|
346
|
+
| | `ip_literal_not_allowed` | An IP address as domain (`user@[192.0.2.1]`), and `allowIpLiteral` is off. |
|
|
347
|
+
| | `ip_literal_invalid` | A malformed IP address in brackets. |
|
|
348
|
+
| disposable | `disposable` | The domain (or a parent domain) is on the built-in disposable list. |
|
|
349
|
+
| | `blocked` | The domain (or a parent domain) is in `blockDomains`. |
|
|
350
|
+
| role | `role` | A role account, and `rejectRole: true`. |
|
|
351
|
+
| mx | `domain_not_found` | The domain does not exist (NXDOMAIN). |
|
|
352
|
+
| | `no_mx` | The domain exists but has no MX records and no A/AAAA address. |
|
|
353
|
+
| | `null_mx` | The domain says it accepts no email (RFC 7505 null MX, `MX 0 .`). |
|
|
354
|
+
| | `timeout` | DNS did not answer within `timeout`. Status `'error'`. |
|
|
355
|
+
| | `dns_error` | DNS failed, for example SERVFAIL or no network. Status `'error'`; the DNS code is in `checks.mx.code`. |
|
|
356
|
+
|
|
357
|
+
## API
|
|
358
|
+
|
|
359
|
+
All functions are named exports. The default export `validmail` is a function that also carries every function as a property: `validmail.sync`, `validmail.validateMany`, `validmail.checkSyntax`, and so on. With CommonJS, `require('validmail')` returns that same function, so `const { validateSync } = require('validmail')` also works.
|
|
360
|
+
|
|
361
|
+
### validmail(email, options?)
|
|
362
|
+
|
|
363
|
+
```ts
|
|
364
|
+
function validmail(email: string, options?: ValidmailOptions): Promise<ValidationResult>
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
Runs every check, including DNS. It never rejects for a bad address; it rejects only when `options.signal` aborts. `validate(email, options?)` is the same function as a named export.
|
|
368
|
+
|
|
369
|
+
**Syntax options** (also used by `validateSync`, `validateMany`, `checkSyntax`, `isValidEmail`):
|
|
370
|
+
|
|
371
|
+
| Option | Type | Default | Description |
|
|
372
|
+
|---|---|---|---|
|
|
373
|
+
| `allowQuoted` | `boolean` | `false` | Accept quoted local parts: `"john doe"@example.com`. |
|
|
374
|
+
| `allowIpLiteral` | `boolean` | `false` | Accept `user@[192.0.2.1]` and `user@[IPv6:2001:db8::1]`. The disposable and DNS checks are skipped for these. |
|
|
375
|
+
| `allowUnicodeLocal` | `boolean` | `false` | Accept non-ASCII characters before the `@` (`josé@example.com`, RFC 6531). Many mail servers still reject them. Unicode **domains** are always accepted. |
|
|
376
|
+
| `requireTld` | `boolean` | `true` | Require a dot in the domain. Set `false` for intranet hosts like `user@localhost`. |
|
|
377
|
+
|
|
378
|
+
**Domain and role options** (also used by `validateSync`, `validateMany`, `isValidEmail`):
|
|
379
|
+
|
|
380
|
+
| Option | Type | Default | Description |
|
|
381
|
+
|---|---|---|---|
|
|
382
|
+
| `disposable` | `boolean` | `true` | Reject known disposable domains. `false` only flags them in `checks.disposable.isDisposable`. |
|
|
383
|
+
| `blockDomains` | `Iterable<string>` | none | Array or Set of extra domains to reject, subdomains included. A leading `@` or `.` is ignored. Applies even with `disposable: false`. |
|
|
384
|
+
| `allowDomains` | `Iterable<string>` | none | Domains exempt from the built-in disposable list, subdomains included. Does not override `blockDomains`. |
|
|
385
|
+
| `rejectRole` | `boolean` | `false` | Reject role accounts (`admin@`, `info@`, `support@`, `noreply@`, ...). By default they are only flagged in `checks.role`. |
|
|
386
|
+
|
|
387
|
+
**DNS options** (also used by `validateMany`, `checkMx`, `isValidEmailAsync`):
|
|
388
|
+
|
|
389
|
+
| Option | Type | Default | Description |
|
|
390
|
+
|---|---|---|---|
|
|
391
|
+
| `mx` | `boolean` | `true` | Check that the domain can receive email. `false` skips DNS. Not used by `checkMx`. |
|
|
392
|
+
| `timeout` | `number` | `5000` | Milliseconds before the DNS check gives up (`status: 'error'`, `reason: 'timeout'`). Covers the MX query and the A/AAAA fallback. `0` turns it off. |
|
|
393
|
+
| `allowDnsErrors` | `boolean` | `false` | Count DNS timeouts and failures as valid. `checks.mx.status` is still `'error'`. Not used by `checkMx`. |
|
|
394
|
+
| `implicitMx` | `boolean` | `true` | Accept domains without MX records that have an A or AAAA address (RFC 5321 §5.1). `false` requires real MX records. |
|
|
395
|
+
| `resolver` | `Resolver` | system DNS | Object with `resolveMx(host)` and optionally `resolve4(host)` / `resolve6(host)`, all returning promises. `dns.promises`, `new dns.promises.Resolver()` and test fakes fit. |
|
|
396
|
+
| `cache` | `boolean \| Map` | `true` | `true`: built-in in-memory cache (one per resolver, at most 10,000 domains). `false`: no cache. A `Map`: your own cache, which you can share or inspect. Only definite answers are cached. |
|
|
397
|
+
| `cacheTtl` | `number` | `3600000` | Milliseconds a cached result stays fresh (1 hour). |
|
|
398
|
+
| `signal` | `AbortSignal` | none | Cancels the check. The promise rejects with `signal.reason`. |
|
|
399
|
+
|
|
400
|
+
### validateSync(email, options?)
|
|
401
|
+
|
|
402
|
+
```ts
|
|
403
|
+
function validateSync(email: string, options?: SyncOptions): ValidationResult
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
The same checks without DNS: syntax, disposable, block list and role. Takes the syntax, domain and role options. `checks.mx.status` is always `'skip'`. Also available as `validmail.sync`.
|
|
407
|
+
|
|
408
|
+
### validateMany(emails, options?)
|
|
409
|
+
|
|
410
|
+
```ts
|
|
411
|
+
function validateMany(emails: Iterable<string>, options?: ValidateManyOptions): Promise<ValidationResult[]>
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
Validates an array (or any iterable) and returns results in input order. Takes all `validmail()` options, plus:
|
|
415
|
+
|
|
416
|
+
| Option | Type | Default | Description |
|
|
417
|
+
|---|---|---|---|
|
|
418
|
+
| `concurrency` | `number` | `10` | Maximum number of addresses checked at the same time. Must be a positive integer, or the function throws a `RangeError`. |
|
|
419
|
+
|
|
420
|
+
### checkSyntax(email, options?)
|
|
421
|
+
|
|
422
|
+
```ts
|
|
423
|
+
function checkSyntax(email: string, options?: SyntaxOptions): SyntaxResult
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
Syntax only. Returns `{ valid, reason?, message?, email, local, domain, asciiDomain, quoted, ipLiteral }`. Takes the syntax options. Input longer than 254 characters is rejected before it is scanned.
|
|
427
|
+
|
|
428
|
+
### checkMx(domainOrEmail, options?)
|
|
429
|
+
|
|
430
|
+
```ts
|
|
431
|
+
function checkMx(domainOrEmail: string, options?: MxOptions): Promise<MxCheck>
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
DNS only. Accepts a domain or a full address. Returns `{ status, reason?, message?, records?, implicit?, cached?, code? }`. Takes the DNS options. Throws a `TypeError` if the domain is not a valid host name.
|
|
435
|
+
|
|
436
|
+
```js
|
|
437
|
+
await checkMx('gmail.com') // => { status: 'pass', records: [{ exchange: 'gmail-smtp-in.l.google.com', priority: 5 }, ...] }
|
|
438
|
+
await checkMx('example.com') // => { status: 'fail', reason: 'null_mx', message: '...' }
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
### isValidEmail(email, options?)
|
|
442
|
+
|
|
443
|
+
```ts
|
|
444
|
+
function isValidEmail(email: string, options?: SyncOptions): boolean
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
Short for `validateSync(email, options).valid`. Synchronous, no DNS.
|
|
448
|
+
|
|
449
|
+
### isValidEmailAsync(email, options?)
|
|
450
|
+
|
|
451
|
+
```ts
|
|
452
|
+
function isValidEmailAsync(email: string, options?: ValidmailOptions): Promise<boolean>
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
Short for `(await validmail(email, options)).valid`.
|
|
456
|
+
|
|
457
|
+
### isDisposable(emailOrDomain)
|
|
458
|
+
|
|
459
|
+
```ts
|
|
460
|
+
function isDisposable(emailOrDomain: string): boolean
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
`true` if the domain, or a parent domain, is on the built-in disposable list. `isDisposable('x@sub.mailinator.com')` is `true`.
|
|
464
|
+
|
|
465
|
+
### isRoleAccount(emailOrLocal)
|
|
466
|
+
|
|
467
|
+
```ts
|
|
468
|
+
function isRoleAccount(emailOrLocal: string): boolean
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
`true` for role mailboxes, ignoring case and `+tags`. `isRoleAccount('Support+billing@example.com')` is `true`.
|
|
472
|
+
|
|
473
|
+
### disposableDomains
|
|
474
|
+
|
|
475
|
+
```ts
|
|
476
|
+
const disposableDomains: readonly string[]
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
The built-in disposable list: lowercase ASCII, sorted, frozen.
|
|
480
|
+
|
|
481
|
+
### clearCache()
|
|
482
|
+
|
|
483
|
+
```ts
|
|
484
|
+
function clearCache(): void
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
Empties the built-in DNS caches. A `Map` you passed as `cache` is not touched.
|
|
488
|
+
|
|
489
|
+
### Types
|
|
490
|
+
|
|
491
|
+
`ValidationResult`, `ValidmailOptions`, `SyncOptions`, `SyntaxOptions`, `MxOptions`, `ValidateManyOptions`, `Checks`, `SyntaxCheck`, `DisposableCheck`, `RoleCheck`, `MxCheck`, `MxRecord`, `MxCacheEntry`, `Resolver`, `Reason`, `SyntaxReason`, `MxReason`, `DisposableReason`, `CheckStatus`, `SyntaxResult`, `EmailParts`, `Outcome`, `Validmail`.
|
|
492
|
+
|
|
493
|
+
## Comparison
|
|
494
|
+
|
|
495
|
+
| | `deep-email-validator` | `email-validator` | `email-existence` | `mailchecker` | **validmail** |
|
|
496
|
+
|---|---|---|---|---|---|
|
|
497
|
+
| Syntax | One `@`, a dot in the domain, no whitespace | Regex + 254/64/63 length limits | `\S+@\S+` | Full RFC regex | RFC 5321/5322 with lengths, dot rules, options for quoted / IP literal / UTF-8 |
|
|
498
|
+
| Unicode (IDN) domains | Passed to DNS unconverted | No (rejected) | Passed to DNS unconverted | No (rejected) | Yes (converted to punycode) |
|
|
499
|
+
| Disposable domains | Yes (large list, exact match only) | No | No | Yes (~56,000, subdomain-aware) | Yes (~590 curated, subdomain-aware, block/allow lists) |
|
|
500
|
+
| MX lookup | Yes | No | Yes | No | Yes |
|
|
501
|
+
| A/AAAA fallback (RFC 5321 §5.1) | No | n/a | No | n/a | Yes |
|
|
502
|
+
| Null MX (RFC 7505) | No | n/a | No | n/a | Yes (`reason: 'null_mx'`) |
|
|
503
|
+
| DNS error vs. "no mail server" | No (any DNS error means "MX record not found") | n/a | No | n/a | Yes (`status: 'error'` vs `'fail'`, `allowDnsErrors`) |
|
|
504
|
+
| DNS timeout | No | n/a | No (SMTP timeout only) | n/a | Yes (`timeout`, `AbortSignal`) |
|
|
505
|
+
| Custom / fake DNS resolver | No | n/a | No | n/a | Yes |
|
|
506
|
+
| Cache + shared in-flight lookups | No | n/a | No | n/a | Yes |
|
|
507
|
+
| SMTP `RCPT TO` probing | Yes (**on by default**, port 25) | No | Yes (its main feature) | No | No ([by design](#why-no-smtp-check)) |
|
|
508
|
+
| Says which check failed | Yes | No (boolean) | No (boolean) | No (boolean) | Yes (reason code + message per check) |
|
|
509
|
+
| API | Promise | Sync | Callback | Sync | Promise + sync |
|
|
510
|
+
| Runtime dependencies | 2 | 0 | 1 | 0 | 0 |
|
|
511
|
+
| Unpacked size | 13 MB | 12 KB | 4 KB | 1 MB | 87 KB |
|
|
512
|
+
| TypeScript types | Yes | Yes | No | Yes | Yes |
|
|
513
|
+
|
|
514
|
+
Compared with `deep-email-validator@0.1.27`, `email-validator@2.0.4`, `email-existence@0.1.6` and `mailchecker@6.0.21`.
|
|
515
|
+
|
|
516
|
+
`deep-email-validator` also runs a typo check by default and marks an address invalid when `mailcheck` suggests a different domain. validmail does not guess: typo suggestions belong in the form (see [inboxok](https://www.npmjs.com/package/inboxok)). If you need the largest disposable list, use `mailchecker`'s list as `blockDomains` (see [Block or allow more domains](#block-or-allow-more-domains)).
|
|
517
|
+
|
|
518
|
+
## Notes and limitations
|
|
519
|
+
|
|
520
|
+
- **It cannot prove that a mailbox exists.** Only a confirmation email can (see [Why no SMTP check?](#why-no-smtp-check)).
|
|
521
|
+
- **No typo suggestions** (`gmial.com` to `gmail.com`). That belongs in the form, before submit: use [inboxok](https://www.npmjs.com/package/inboxok). Common typo domains are often registered and accept email (`gmial.com` passes the MX check), so DNS alone does not catch them.
|
|
522
|
+
- **Provider aliases are not merged.** Gmail dots and `+tags` are kept as typed in the part before the `@`.
|
|
523
|
+
- **The disposable list is not complete.** New services appear every day; the built-in list covers the common ones. Add more with `blockDomains`.
|
|
524
|
+
- **IP address domains** (`user@[192.0.2.1]`, with `allowIpLiteral`) skip the disposable and DNS checks.
|
|
525
|
+
- **Errors and timeouts are not cached**, so the next check asks DNS again.
|
|
526
|
+
|
|
527
|
+
### Why no SMTP check?
|
|
528
|
+
|
|
529
|
+
Some validators connect to the recipient's mail server and send `RCPT TO` to ask whether the mailbox exists. validmail does not do this, on purpose:
|
|
530
|
+
|
|
531
|
+
- **It is not reliable.** Catch-all domains accept every address. Other servers delay the first try (greylisting), limit the number of requests, or refuse to answer unknown senders, to stop address harvesting. You get "valid" for addresses that do not exist and "invalid" for real ones.
|
|
532
|
+
- **It gets you blocked.** Opening port 25 connections and closing them before sending looks like a spammer collecting addresses. Providers may block your server's IP, which can hurt the real email you send.
|
|
533
|
+
- **It often cannot run at all.** Most cloud and hosting providers block outgoing port 25 by default, so the check just times out.
|
|
534
|
+
- **It is slow.** It takes seconds per address, which is too long for a sign-up request.
|
|
535
|
+
|
|
536
|
+
The only reliable way to know that a mailbox exists is to send a confirmation email. validmail catches everything you can know without sending one: bad syntax, disposable services, and domains that cannot receive email.
|
|
537
|
+
|
|
538
|
+
## Requirements
|
|
539
|
+
|
|
540
|
+
- Node.js 20 or later. Bun and Deno also work: validmail uses only `node:dns`, `node:net` and `node:url`, which they provide.
|
|
541
|
+
- Server only: it needs DNS. In the browser, use [inboxok](https://www.npmjs.com/package/inboxok).
|
|
542
|
+
- ESM and CommonJS builds.
|
|
543
|
+
- TypeScript types included.
|
|
544
|
+
- Zero dependencies. Network calls are DNS lookups only.
|
|
545
|
+
|
|
16
546
|
## License
|
|
17
547
|
|
|
18
548
|
MIT
|