Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

📨 Validate an email address in Go

mail

Please consider supporting us by disabling your ad blocker

An email address in Golang can be validated using the standard library function mail.ParseAddress. This function parses an RFC 5322 address, but by using it appropriately, we can also check if a string is a valid email address and get it from the "name <local-part@domain>" format.

package main

import (
    "fmt"
    "net/mail"
)

func validMailAddress(address string) (string, bool) {
    addr, err := mail.ParseAddress(address)
    if err != nil {
        return "", false
    }
    return addr.Address, true
}

var addresses = []string{
    "foo@gmail.com",
    "Gopher <from@example.com>",
    "example",
}

func main() {
    for _, a := range addresses {
        if addr, ok := validMailAddress(a); ok {
            fmt.Printf("value: %-30s valid email: %-10t address: %s\n", a, ok, addr)
        } else {
            fmt.Printf("value: %-30s valid email: %-10t\n", a, ok)
        }
    }
}

Output:

value: foo@gmail.com                  valid email: true       address: foo@gmail.com
value: Gopher <from@example.com>      valid email: true       address: from@example.com
value: example                        valid email: false