What we'll build
A regular expression or net/mail.ParseAddress() can tell you an address looks right. Neither can tell you whether the domain exists, whether it accepts mail, or whether it's a throwaway inbox. In this guide we'll build a ValidateEmail() function in Go that checks all of those and returns one of four statuses:
| Status | Meaning | Typical action |
|---|---|---|
valid | Well formed, and the domain accepts mail | Accept |
invalid | Bad syntax, no such domain, or no mail server | Reject and ask the user to fix it |
risky | Disposable, a likely typo, a role account, or no MX records | Your call: block, warn, or flag |
unknown | DNS failed temporarily | Accept and check again later |
You'll need Go 1.26 or later, which the current releases of x/net require. Add the two dependencies: miekg/dns for DNS lookups (step 2 explains why the standard library isn't enough) and x/net/idna for international domain names:
go get github.com/miekg/dns golang.org/x/net/idnaAll the code lives in one package, emailcheck, and was tested with Go 1.26, miekg/dns 1.1 and Gin 1.12. Want to see the end result first? The free email checker runs the same checks.
1. Check the syntax
Start with the check that needs no network. Instead of one huge regular expression, split the address at the last @ and check each part separately. The rules stay readable, and you can say exactly what's wrong:
package emailcheck
import (
"regexp"
"strings"
"golang.org/x/net/idna"
)
var (
// RFC 5322 "atext": the characters allowed in each dot-separated part of the local part.
atom = regexp.MustCompile("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+$")
// A DNS label: letters, digits and hyphens, not starting or ending with a hyphen.
label = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$`)
digits = regexp.MustCompile(`^[0-9]+$`)
)
type Syntax struct {
OK bool
Reason string
Local string
Domain string
Normalized string
}
func CheckSyntax(input string) Syntax {
email := strings.TrimSpace(input)
if len(email) > 254 {
return Syntax{Reason: "too_long"}
}
at := strings.LastIndex(email, "@")
if at <= 0 || at == len(email)-1 {
return Syntax{Reason: "missing_at_or_part"}
}
local := email[:at]
if len(local) > 64 { // len() counts bytes, which is what RFC 5321 limits
return Syntax{Reason: "local_part_too_long"}
}
// Splitting on "." also rejects leading, trailing and doubled dots (they create empty atoms).
for _, a := range strings.Split(local, ".") {
if !atom.MatchString(a) {
return Syntax{Reason: "invalid_local_part"}
}
}
// idna.Lookup lower-cases the domain and converts international names to punycode.
domain, err := idna.Lookup.ToASCII(strings.TrimSuffix(email[at+1:], "."))
labels := strings.Split(domain, ".")
if err != nil || len(labels) < 2 || digits.MatchString(labels[len(labels)-1]) {
return Syntax{Reason: "invalid_domain"}
}
for _, l := range labels {
if !label.MatchString(l) {
return Syntax{Reason: "invalid_domain"}
}
}
return Syntax{OK: true, Local: local, Domain: domain, Normalized: strings.ToLower(local) + "@" + domain}
}Notes on the code:
idna.Lookup.ToASCII()converts international domains to punycode (münchen.debecomesxn--mnchen-3ya.de), which is the form DNS needs, and lower-cases them. It returns an error for names it can't convert.- Splitting the local part on dots means
.jane,jane.andja..neall produce an empty part that fails, with no extra rules. - The length limits come from RFC 5321: 64 bytes for the local part and 254 characters overall. Go's
len()counts bytes, which is exactly what the limit means.
mail.ParseAddress() parses full headers like "Jane" <jane@example.com> and accepts quoted local parts and comments, which almost never belong in a sign-up form. A dedicated check like this one is stricter and gives you a reason.Only lower-case the local part when comparing addresses, to stop duplicate sign-ups. Store what the user typed, because a few mail servers still treat Jane and jane as different mailboxes.
2. Check the domain's MX records
A well-formed address is no use if its domain doesn't exist or doesn't accept mail. The domain's MX (mail exchanger) records name the servers that receive its mail.
Go's net.LookupMX() has a catch: it returns the same "no such host" error, with IsNotFound set, both for a domain that doesn't exist and for a domain that exists but has no MX records. Those need different answers, so we use miekg/dns, which gives us the DNS response code:
package emailcheck
import (
"net"
"sort"
"time"
"github.com/miekg/dns"
)
// DNSServer is the resolver to ask: the first nameserver in /etc/resolv.conf.
var DNSServer = func() string {
conf, err := dns.ClientConfigFromFile("/etc/resolv.conf")
if err != nil || len(conf.Servers) == 0 {
return "1.1.1.1:53"
}
return net.JoinHostPort(conf.Servers[0], conf.Port)
}()
// A short timeout, so a slow DNS server can't stall a sign-up.
var client = &dns.Client{Timeout: 3 * time.Second}
type DomainCheck struct {
Status string // "ok", "risky", "invalid" or "unknown"
Reason string
MX []string
}
func query(domain string, qtype uint16) (*dns.Msg, error) {
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(domain), qtype)
r, _, err := client.Exchange(m, DNSServer)
if err == nil && r.Truncated { // answer too big for UDP: ask again over TCP
r, _, err = (&dns.Client{Net: "tcp", Timeout: client.Timeout}).Exchange(m, DNSServer)
}
return r, err
}
func CheckDomain(domain string) DomainCheck {
r, err := query(domain, dns.TypeMX)
switch {
case err != nil:
// Timeouts and network errors are temporary. Don't blame the user.
return DomainCheck{Status: "unknown", Reason: "dns_error"}
case r.Rcode == dns.RcodeNameError:
return DomainCheck{Status: "invalid", Reason: "domain_not_found"}
case r.Rcode != dns.RcodeSuccess:
return DomainCheck{Status: "unknown", Reason: "dns_error"} // SERVFAIL, REFUSED…
}
var mx []*dns.MX
for _, rr := range r.Answer {
if m, ok := rr.(*dns.MX); ok {
mx = append(mx, m)
}
}
// RFC 7505 "null MX": a single record pointing at "." means "this domain accepts no mail".
if len(mx) == 1 && mx[0].Mx == "." {
return DomainCheck{Status: "invalid", Reason: "domain_rejects_mail"}
}
if len(mx) > 0 {
sort.Slice(mx, func(i, j int) bool { return mx[i].Preference < mx[j].Preference })
hosts := make([]string, len(mx))
for i, m := range mx {
hosts[i] = m.Mx
}
return DomainCheck{Status: "ok", MX: hosts}
}
// No MX records: mail servers fall back to the domain's own A/AAAA record ("implicit MX").
for _, t := range []uint16{dns.TypeA, dns.TypeAAAA} {
if r, err := query(domain, t); err == nil && len(r.Answer) > 0 {
return DomainCheck{Status: "risky", Reason: "no_mx_records"}
}
}
return DomainCheck{Status: "invalid", Reason: "no_mail_server"}
}| Result | Meaning | Status |
|---|---|---|
| MX records returned | The domain accepts mail | ok |
| One MX record with an empty name | "Null MX" (RFC 7505): the domain accepts no mail | invalid |
Rcode is RcodeNameError (NXDOMAIN) | The domain doesn't exist | invalid |
RcodeSuccess but no MX in the answer | The domain exists but has no MX records, so check A/AAAA | risky or invalid |
Another Rcode, or an error from Exchange | SERVFAIL or a timeout: DNS trouble, not the user's fault | unknown |
Keep the client's timeout short, so a slow DNS server can't hold up a sign-up, and never treat a timeout as "invalid", or you'll turn away real users whenever DNS has a bad moment.
3. Cache DNS lookups
Most of your users share a handful of domains like gmail.com and outlook.com. A Go server is one long-running process, so an in-memory map shared by all requests saves most lookups:
package emailcheck
import (
"sync"
"time"
)
type cached struct {
result DomainCheck
expires time.Time
}
var (
cacheMu sync.Mutex
cache = map[string]cached{}
)
func CheckDomainCached(domain string) DomainCheck {
cacheMu.Lock()
hit, ok := cache[domain]
cacheMu.Unlock()
if ok && time.Now().Before(hit.expires) {
return hit.result
}
result := CheckDomain(domain)
if result.Status != "unknown" { // don't remember temporary failures
cacheMu.Lock()
cache[domain] = cached{result, time.Now().Add(time.Hour)}
cacheMu.Unlock()
}
return result
}The mutex makes the map safe to use from many goroutines at once. Two sign-ups for the same new domain at the same moment may both query DNS, which is harmless; if you want exactly one query, wrap CheckDomain with golang.org/x/sync/singleflight. Don't cache failed lookups.
4. Detect disposable domains
Temporary inboxes from services like Mailinator pass every check so far: the syntax is fine and the domains have working mail servers. The only way to catch them is a list. Download the community-maintained disposable-email-domains list next to your binary:
curl -fsSo disposable_email_blocklist.conf https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/main/disposable_email_blocklist.confpackage emailcheck
import (
"os"
"strings"
"sync"
)
var blocklist = sync.OnceValue(func() map[string]bool {
// One domain per line. A map makes each lookup instant.
data, err := os.ReadFile("disposable_email_blocklist.conf")
if err != nil {
panic(err)
}
set := map[string]bool{}
for _, line := range strings.Split(string(data), "\n") {
if line = strings.TrimSpace(line); line != "" {
set[line] = true
}
}
return set
})
// IsDisposable checks the domain and each parent, so "x.mailinator.com" matches "mailinator.com".
func IsDisposable(domain string) bool {
labels := strings.Split(domain, ".")
for i := 0; i < len(labels)-1; i++ {
if blocklist()[strings.Join(labels[i:], ".")] {
return true
}
}
return false
}sync.OnceValue loads the file the first time it's needed and never again. Checking parent domains matters because many disposable services hand out addresses on random subdomains. New disposable domains appear every week, so download the list again from a daily job. To ship a single binary, swap os.ReadFile for an //go:embed variable.
The list also contains some typo domains, such as gmial.com and hotmial.com. Someone registered them to collect mail meant for Gmail and Hotmail users, which is why step 6 still returns a DidYouMean suggestion for a disposable address. Read more about how disposable email detection works.
5. Flag role accounts and suggest typo fixes
Flag role accounts and typos too. Role accounts like info@ and support@ reach a shared inbox rather than a person, and typos like gamil.com are one of the commonest reasons a sign-up email never arrives:
package emailcheck
import (
"slices"
"strings"
)
var roleAccounts = []string{
"admin", "billing", "contact", "help", "hello", "info", "marketing", "no-reply",
"noreply", "office", "postmaster", "sales", "support", "team", "webmaster",
}
func IsRoleAccount(local string) bool {
// Ignore "+tag" sub-addressing: "support+billing" is still "support".
base, _, _ := strings.Cut(strings.ToLower(local), "+")
return slices.Contains(roleAccounts, base)
}
// Real providers people mistype. Include close neighbours (mail.com, ymail.com, gmx.com…)
// too, or they'd be "corrected" to the provider one letter away.
var popularDomains = []string{
"gmail.com", "googlemail.com", "yahoo.com", "ymail.com", "yahoo.co.uk", "hotmail.com",
"hotmail.co.uk", "outlook.com", "live.com", "msn.com", "icloud.com", "me.com", "mac.com",
"aol.com", "mail.com", "gmx.com", "gmx.de", "proton.me", "protonmail.com",
}
// editDistance is the Levenshtein distance: the number of single-character edits between a and b.
func editDistance(a, b string) int {
prev := make([]int, len(b)+1)
for j := range prev {
prev[j] = j
}
for i := 1; i <= len(a); i++ {
row := make([]int, len(b)+1)
row[0] = i
for j := 1; j <= len(b); j++ {
cost := 1
if a[i-1] == b[j-1] {
cost = 0
}
row[j] = min(prev[j]+1, row[j-1]+1, prev[j-1]+cost)
}
prev = row
}
return prev[len(b)]
}
// SuggestDomain returns "gmail.com" for "gmial.com", or "" when the domain is fine or nothing is close.
func SuggestDomain(domain string) string {
if slices.Contains(popularDomains, domain) {
return ""
}
best, bestDistance := "", 1<<30
for _, candidate := range popularDomains {
if d := editDistance(domain, candidate); d < bestDistance {
best, bestDistance = candidate, d
}
}
// Short domains only get one edit's leeway: two letters off "me.com" is a different domain.
limit := 2
if len(domain) <= 6 {
limit = 1
}
if bestDistance <= limit {
return best
}
return ""
}The Levenshtein distance counts two swapped letters (gmial → gmail) as two edits, which the two-edit limit for longer domains still allows. Short domains only get one edit's leeway, because a two-letter difference on me.com is a different domain. Domains are ASCII after step 1, so indexing bytes is safe here.
Choose the list of domains carefully. Real providers that sit one letter apart, like mail.com and gmail.com, must both be in it, or users of one get "corrected" to the other. Even then, some genuine domains will look like typos, so show the result as a suggestion and let the user decide.
6. Put it together
Now run the checks from cheapest to most expensive and return a single verdict:
package emailcheck
type Verdict struct {
Status string `json:"status"` // "valid", "invalid", "risky" or "unknown"
Reason string `json:"reason"`
Email string `json:"email,omitempty"`
DidYouMean *string `json:"did_you_mean"`
}
func ValidateEmail(input string) Verdict {
s := CheckSyntax(input)
if !s.OK {
return Verdict{Status: "invalid", Reason: s.Reason}
}
v := Verdict{Email: s.Normalized}
suggestion := SuggestDomain(s.Domain)
if suggestion != "" {
fixed := s.Local + "@" + suggestion
v.DidYouMean = &fixed
}
dns := CheckDomainCached(s.Domain)
if dns.Status == "invalid" || dns.Status == "unknown" {
v.Status, v.Reason = dns.Status, dns.Reason
return v
}
// The domain can receive mail. Now look for risk signals, most serious first.
switch {
case IsDisposable(s.Domain):
v.Status, v.Reason = "risky", "disposable"
case suggestion != "":
v.Status, v.Reason = "risky", "possible_typo"
case dns.Status == "risky":
v.Status, v.Reason = "risky", dns.Reason
case IsRoleAccount(s.Local):
v.Status, v.Reason = "risky", "role_based"
default:
v.Status, v.Reason = "valid", "mail_server_found"
}
return v
}DidYouMean is a pointer so it encodes as JSON null when there's no suggestion. ValidateEmail() returns these results for a range of inputs:
| Input | status | reason | DidYouMean |
|---|---|---|---|
jane@gmail.com | valid | mail_server_found | nil |
joe@gamil.com | risky | possible_typo | joe@gmail.com |
test@mailinator.com | risky | disposable | nil |
support@acme.io | risky | role_based | nil |
x@no-such-domain.example | invalid | domain_not_found | nil |
not-an-email | invalid | missing_at_or_part | nil |
7. Use it in a net/http handler or Gin
A typical sign-up policy is to reject invalid and disposable addresses, accept everything else, and pass the typo suggestion back so the front end can ask "Did you mean …?". As a plain net/http handler:
package emailcheck
import (
"encoding/json"
"net/http"
)
// SignupHandler serves POST /signup with a JSON body {"email": "..."}.
func SignupHandler(w http.ResponseWriter, r *http.Request) {
var body struct {
Email string `json:"email"`
}
_ = json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&body)
result := ValidateEmail(body.Email)
w.Header().Set("Content-Type", "application/json")
if result.Status == "invalid" || result.Reason == "disposable" {
message := "That email address can't receive mail."
if result.Reason == "disposable" {
message = "Please use a permanent email address."
}
w.WriteHeader(http.StatusUnprocessableEntity)
json.NewEncoder(w).Encode(map[string]any{"error": message, "did_you_mean": result.DidYouMean})
return
}
// "unknown" means DNS had a hiccup. Accept the address and check it again later.
// createUser(result.Email)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]any{"ok": true, "email": result.Email, "did_you_mean": result.DidYouMean})
}Register it with http.HandleFunc("POST /signup", emailcheck.SignupHandler); the standard router matches the method for you. In Gin, request validation runs through go-playground/validator, so register a deliverable tag and use it next to the built-in email tag:
package main
import (
"net/http"
"example.com/emailcheck"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)
type SignupRequest struct {
Email string `json:"email" binding:"required,email,deliverable"`
}
// deliverable rejects addresses that can't receive mail and disposable inboxes.
var deliverable validator.Func = func(fl validator.FieldLevel) bool {
result := emailcheck.ValidateEmail(fl.Field().String())
return result.Status != "invalid" && result.Reason != "disposable"
}
func setupRouter() *gin.Engine {
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("deliverable", deliverable)
}
r := gin.Default()
r.POST("/signup", func(c *gin.Context) {
var req SignupRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Please use a working, permanent email address."})
return
}
// createUser(req.Email)
c.JSON(http.StatusCreated, gin.H{"ok": true})
})
return r
}
func main() {
setupRouter().Run(":8080")
}Adjust the policy to your product: a B2B form might also reject free providers, while a newsletter might accept role accounts.
8. Test it
The syntax check has no side effects, so a plain table-driven test covers it:
package emailcheck
import "testing"
func TestCheckSyntax(t *testing.T) {
for _, email := range []string{"jane@example.com", "jane.doe+news@example.co.uk", "user@münchen.de"} {
if !CheckSyntax(email).OK {
t.Errorf("%q should be accepted", email)
}
}
for _, email := range []string{"", "jane", "@example.com", "jane@", "a..b@example.com", "jane@example", "jane@-example.com"} {
if CheckSyntax(email).OK {
t.Errorf("%q should be rejected", email)
}
}
}For the DNS checks, set emailcheck.DNSServer = "127.0.0.1:5353" and run a local test DNS server. Then go test doesn't depend on the internet. That's how we tested every result on this page.
What about checking that the mailbox exists?
You could go further with net/smtp: connect to the domain's mail server on port 25 and ask whether a specific mailbox exists with RCPT TO. We don't recommend doing that inside a request. Many hosting providers block outbound port 25, large providers often accept every recipient at that stage, and catch-all domains and greylisting make the answer inconclusive.
For most sign-up forms, the checks above plus a confirmation email are the best balance of accuracy and speed.
Or use an email validation API
Everything above works, but you have to maintain it: the disposable list goes stale, the typo list needs tuning, and DNS edge cases keep turning up. The validateemail.io API runs all of these checks in one request:
package emailcheck
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
)
const apiBase = "https://validateemail.io/v1"
type APIResult struct {
Email string `json:"email"`
Status string `json:"status"`
Reason string `json:"reason"`
DidYouMean *string `json:"did_you_mean"`
Score float64 `json:"score"`
}
func apiRequest(path string, body any, timeout time.Duration, out any) error {
payload, _ := json.Marshal(body)
req, _ := http.NewRequest(http.MethodPost, apiBase+path, bytes.NewReader(payload))
req.Header.Set("Authorization", "Bearer "+os.Getenv("VALIDATEEMAIL_KEY"))
req.Header.Set("Content-Type", "application/json")
res, err := (&http.Client{Timeout: timeout}).Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("HTTP %d", res.StatusCode)
}
return json.NewDecoder(res.Body).Decode(out)
}
func ValidateWithAPI(email string) APIResult {
var result APIResult
if err := apiRequest("/validate", map[string]string{"email": email}, 5*time.Second, &result); err != nil {
// Never block a sign-up because the validator is slow or unreachable.
log.Printf("email validation unavailable: %v", err)
return APIResult{Email: email, Status: "unknown", Reason: "validator_unavailable"}
}
return result
}
// ValidateList validates any number of addresses, 100 per request.
func ValidateList(emails []string) ([]APIResult, error) {
var all []APIResult
for i := 0; i < len(emails); i += 100 {
var page struct{ Results []APIResult }
if err := apiRequest("/validate/batch", map[string]any{"emails": emails[i:min(i+100, len(emails))]}, 30*time.Second, &page); err != nil {
return all, err
}
all = append(all, page.Results...)
}
return all, nil
}If the API is slow or unreachable, ValidateWithAPI() returns unknown instead of an error, so a network problem never blocks a sign-up. The response has the same status, reason and did_you_mean fields used in this guide, plus a score and the result of every individual check.
Using an AI coding assistant? Paste this prompt and it will wire up the API for you:
Add email validation to the sign-up handler of this Go app using the validateemail.io API (reference: https://validateemail.io/llms.txt).
- Call POST https://validateemail.io/v1/validate from server-side code only, with the header "Authorization: Bearer <key>" read from the VALIDATEEMAIL_KEY environment variable, and the JSON body {"email": "<address>"}. Never call it from the browser.
- Reject the address with a clear message when "status" is "invalid" or "checks.disposable" is true.
- When "did_you_mean" is set, show "Did you mean <did_you_mean>?" and let the user accept the fix.
- Use a 5-second timeout. If the API fails, times out or returns "status": "unknown", accept the address so sign-ups never break.
- Add a test that mocks the API for a valid, an invalid and a disposable address.Frequently asked questions
Is net/mail.ParseAddress() enough to validate an email in Go?
mail.ParseAddress() parses RFC 5322 addresses, including display names and quoted local parts, so it's more permissive than a sign-up form needs. It also can't tell you whether the domain exists or accepts mail, or whether the address is disposable or mistyped. Pair a format check with an MX lookup and the other checks in this guide.
Why not use net.LookupMX in Go?
net.LookupMX() returns the same "no such host" error for a domain that doesn't exist and for a domain with no MX records. Those need different answers: the first is invalid, the second may still receive mail through its A record. miekg/dns exposes the DNS response code, so you can tell them apart.
How do I validate email in Gin?
Gin's binding:"email" tag checks the format only. Register a custom validation with binding.Validator.Engine(), as in step 7, to also reject addresses whose domain can't receive mail and disposable inboxes.
Can Go check that a mailbox exists without sending an email?
You can try by connecting to the domain's mail server on port 25 with net/smtp and sending RCPT TO. In practice port 25 is often blocked, large providers accept every recipient at that stage, and catch-all domains accept anything, so the answer is often unreliable. A confirmation email is still the only definitive test.