Documentation
¶
Overview ¶
Package emailkit is an email validation library that validates email addresses at the syntax, DNS, domain and SMTP levels.
Basic usage:
result, err := emailkit.New().Validate(ctx, "user@example.com")
Full pipeline:
result, err := emailkit.New().
WithDNS().
WithDomain().
WithSMTP(emailkit.SMTPOptions{
HeloDomain: "myapp.com",
MailFrom: "verify@myapp.com",
}).
Validate(ctx, "user@example.com")
Index ¶
- Constants
- Variables
- type CheckLevel
- type CheckResult
- type ConcurrencyOptions
- type DNSOptions
- type DomainOptions
- type Result
- type SMTPOptions
- type Validator
- func (v *Validator) Close() error
- func (v *Validator) Validate(ctx context.Context, email string) (Result, error)
- func (v *Validator) ValidateAll(ctx context.Context, email string) (Result, error)
- func (v *Validator) ValidateMany(ctx context.Context, emails []string, opts ...ConcurrencyOptions) ([]Result, error)
- func (v *Validator) WithDNS(opts ...DNSOptions) *Validator
- func (v *Validator) WithDomain(opts ...DomainOptions) *Validator
- func (v *Validator) WithSMTP(opts SMTPOptions) *Validator
Examples ¶
Constants ¶
const ( LevelSyntax = types.LevelSyntax LevelDNS = types.LevelDNS LevelDomain = types.LevelDomain LevelSMTP = types.LevelSMTP )
Level constants re-exported.
Variables ¶
var ( // ErrNoChecksConfigured is returned when Validate() is called // but no validation level is configured (not even syntax). ErrNoChecksConfigured = errors.New("emailkit: no validation checks configured") // ErrInvalidSMTPOptions is returned when WithSMTP is called // but HeloDomain or MailFrom is missing. ErrInvalidSMTPOptions = errors.New("emailkit: SMTPOptions requires HeloDomain and MailFrom") )
Functions ¶
This section is empty.
Types ¶
type CheckResult ¶
type CheckResult = types.CheckResult
CheckResult is a re-export from the types package so that consumers don't need to import the types package directly.
type ConcurrencyOptions ¶
type ConcurrencyOptions struct {
// Workers is the number of concurrent goroutines. Default: 5
Workers int
}
ConcurrencyOptions configures concurrent processing for ValidateMany.
type DNSOptions ¶
type DNSOptions struct {
// Timeout is the maximum time for MX lookup. Default: 5s
Timeout time.Duration
// FallbackToA when true accepts A records when no MX record is found.
// Default: false (strict MX requirement)
FallbackToA bool
}
DNSOptions configures the DNS validation level.
type DomainOptions ¶
type DomainOptions struct {
// CheckDisposable when true fails on known disposable domains. Default: true
CheckDisposable bool
// CheckTypos when true suggests corrections for close-match domains. Default: true
// This never fails an email, only provides a suggestion (Suggestion field).
CheckTypos bool
// TypoThreshold is the Levenshtein distance threshold for typo detection. Default: 2
TypoThreshold int
}
DomainOptions configures the domain-level validation.
type Result ¶
type Result struct {
Email string `json:"email"`
Valid bool `json:"valid"`
Checks []CheckResult `json:"checks"`
}
Result is the full outcome of an email validation. The Valid field is true only if all configured checks passed.
func (Result) CheckFor ¶
func (r Result) CheckFor(level CheckLevel) (CheckResult, bool)
CheckFor returns the CheckResult for the given level, if it exists. The second return value indicates whether the given level was executed.
Example ¶
package main
import (
"context"
"fmt"
"github.com/optimode/emailkit"
)
func main() {
v := emailkit.New()
result, _ := v.Validate(context.Background(), "user@example.com")
if syntax, ok := result.CheckFor(emailkit.LevelSyntax); ok {
fmt.Println(syntax.Passed, syntax.Details)
}
}
Output: true syntax ok
func (Result) FailedChecks ¶
func (r Result) FailedChecks() []CheckResult
FailedChecks returns those CheckResults that did not pass.
Example ¶
package main
import (
"context"
"fmt"
"github.com/optimode/emailkit"
)
func main() {
v := emailkit.New()
result, _ := v.Validate(context.Background(), "missing-at-sign")
for _, c := range result.FailedChecks() {
fmt.Printf("[%s] %s\n", c.Level, c.Details)
}
}
Output: [syntax] invalid email syntax
type SMTPOptions ¶
type SMTPOptions struct {
// HeloDomain is the domain sent in the EHLO command. Required, e.g. "myapp.com"
HeloDomain string
// MailFrom is the address sent in the MAIL FROM command. Required, e.g. "verify@myapp.com"
MailFrom string
// ConnectTimeout is the maximum time for TCP connection. Default: 5s
ConnectTimeout time.Duration
// CommandTimeout is the maximum response time for SMTP commands. Default: 10s
CommandTimeout time.Duration
// MaxMXHosts is how many MX hosts to try sequentially. Default: 2
MaxMXHosts int
// Port is the SMTP port. Default: 25
Port string
// MaxConnsPerHost is the max pooled SMTP connections per MX host. Default: 3
MaxConnsPerHost int
}
SMTPOptions configures the SMTP probe level.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator is the main fluent builder struct. Instantiate with the New() function. When using SMTP validation, call Close() when done to release pooled connections.
func New ¶
func New() *Validator
New creates a new Validator. By default it only performs syntax checking. Syntax checking always runs and cannot be disabled, because a valid email address is a prerequisite for the other levels.
Example ¶
package main
import (
"context"
"fmt"
"github.com/optimode/emailkit"
)
func main() {
v := emailkit.New()
result, _ := v.Validate(context.Background(), "user@example.com")
fmt.Println(result.Valid)
}
Output: true
func (*Validator) Close ¶
Close releases resources held by the Validator. Must be called when using SMTP validation to close pooled connections. Safe to call multiple times. No-op if no pooled resources exist.
Example ¶
package main
import (
"fmt"
"github.com/optimode/emailkit"
)
func main() {
v := emailkit.New().WithSMTP(emailkit.SMTPOptions{
HeloDomain: "myapp.com",
MailFrom: "verify@myapp.com",
})
defer func() { _ = v.Close() }()
fmt.Println("validator created with SMTP pool")
}
Output: validator created with SMTP pool
func (*Validator) Validate ¶
Validate runs all configured checks on the given email. The pipeline short-circuits: if a level fails, subsequent levels are skipped. Context can be used for timeout or cancellation.
Example ¶
package main
import (
"context"
"fmt"
"github.com/optimode/emailkit"
)
func main() {
v := emailkit.New()
result, _ := v.Validate(context.Background(), "user@example.com")
fmt.Println(result.Valid, result.Checks[0].Details)
result, _ = v.Validate(context.Background(), "invalid")
fmt.Println(result.Valid, result.Checks[0].Details)
}
Output: true syntax ok false invalid email syntax
Example (Idn) ¶
package main
import (
"context"
"fmt"
"github.com/optimode/emailkit"
)
func main() {
v := emailkit.New()
// Internationalized Domain Name (German)
result, _ := v.Validate(context.Background(), "user@münchen.de")
fmt.Println(result.Valid)
// Email Address Internationalization / RFC 6531 (Chinese local part)
result, _ = v.Validate(context.Background(), "用户@example.com")
fmt.Println(result.Valid)
}
Output: true true
func (*Validator) ValidateAll ¶
ValidateAll runs all checks without short-circuiting. Useful when you want to know exactly which levels fail.
Example ¶
package main
import (
"context"
"fmt"
"github.com/optimode/emailkit"
)
func main() {
v := emailkit.New()
result, _ := v.ValidateAll(context.Background(), "bad email")
for _, c := range result.FailedChecks() {
fmt.Printf("[%s] %s\n", c.Level, c.Details)
}
}
Output: [syntax] invalid email syntax
func (*Validator) ValidateMany ¶
func (v *Validator) ValidateMany(ctx context.Context, emails []string, opts ...ConcurrencyOptions) ([]Result, error)
ValidateMany validates multiple emails concurrently. The result order matches the input slice order. Emails are sorted by domain internally for optimal DNS cache and SMTP connection pool utilization.
Example ¶
package main
import (
"context"
"fmt"
"github.com/optimode/emailkit"
)
func main() {
v := emailkit.New()
emails := []string{"alice@example.com", "invalid", "bob@example.com"}
results, _ := v.ValidateMany(context.Background(), emails, emailkit.ConcurrencyOptions{
Workers: 2,
})
for _, r := range results {
fmt.Printf("%-20s valid=%v\n", r.Email, r.Valid)
}
}
Output: alice@example.com valid=true invalid valid=false bob@example.com valid=true
func (*Validator) WithDNS ¶
func (v *Validator) WithDNS(opts ...DNSOptions) *Validator
WithDNS adds MX lookup validation to the pipeline. Optionally overrides the default DNSOptions. MX lookup results are cached and shared with the SMTP checker.
func (*Validator) WithDomain ¶
func (v *Validator) WithDomain(opts ...DomainOptions) *Validator
WithDomain adds domain-level validation (disposable + typo).
Example ¶
package main
import (
"context"
"fmt"
"github.com/optimode/emailkit"
)
func main() {
v := emailkit.New().WithDomain()
// Typo detection (does not fail, populates Suggestion)
result, _ := v.Validate(context.Background(), "user@gmial.com")
domain, _ := result.CheckFor(emailkit.LevelDomain)
fmt.Println(result.Valid, domain.Suggestion)
}
Output: true gmail.com
func (*Validator) WithSMTP ¶
func (v *Validator) WithSMTP(opts SMTPOptions) *Validator
WithSMTP adds the SMTP RCPT TO probe to the pipeline. SMTPOptions.HeloDomain and MailFrom are required. Uses a connection pool for efficient bulk validation (connections reused via RSET). Call Close() when done to release pooled connections.
Directories
¶
| Path | Synopsis |
|---|---|
|
_examples
|
|
|
advanced
command
|
|
|
basic
command
|
|
|
Package check contains the internal validation levels for emailkit.
|
Package check contains the internal validation levels for emailkit. |
|
internal
|
|
|
dnscache
Package dnscache provides a thread-safe, TTL-based cache for DNS MX lookups with singleflight deduplication for concurrent requests to the same domain.
|
Package dnscache provides a thread-safe, TTL-based cache for DNS MX lookups with singleflight deduplication for concurrent requests to the same domain. |
|
smtppool
Package smtppool provides a thread-safe SMTP connection pool that reuses TCP connections via the RSET command for efficient bulk email validation.
|
Package smtppool provides a thread-safe SMTP connection pool that reuses TCP connections via the RSET command for efficient bulk email validation. |
|
Package types contains the shared types for emailkit.
|
Package types contains the shared types for emailkit. |