The standard lib has email parsing and validation built in, simply use: mail.ParseAddress()
.
A simple “is-valid” test:
func valid(email string) bool {
_, err := mail.ParseAddress(email)
return err == nil
}
Testing it:
for _, email := range []string{
"good@exmaple.com",
"bad-example",
} {
fmt.Printf("%18s valid: %t\n", email, valid(email))
}
Which outputs (try it on the Go Playground):
good@exmaple.com valid: true
bad-example valid: false
NOTE:
The net/mail
package implements and follows the RFC 5322 specification (and extension by RFC 6532). This means a seemingly bad email address like bad-example@t
is accepted and parsed by the package because it’s valid according to the spec. t
may be a valid local domain name, it does not necessarily have to be a public domain. net/mail
does not check if the domain part of the address is a public domain, nor that it is an existing, reachable public domain.