How to validate email addresses in Golang

Check if an email address is correct and really exists using the go programming language

Validation in a nutshell

An email address can look right but still be wrong. Real email uses in depths address validation to check if emails really exist without sending any messages.

Checking Formatting

You can use a regular expression to check if an email address is formatted correctly.

package main
import (
"fmt"
"regexp"
)
func main() {
pattern := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
email := "foo@bar.com"
matches := pattern.MatchString(email)
fmt.Printf("email %v matches the pattern %v", email, matches)
}

Real Email API validation

You can use the Real Email API to do in depth email address inspections to check that the address really exists on the email server. In this example we use the go net/http library.

package main
import (
"fmt"
"net/http"
"io/ioutil"
"encoding/json"
"net/url"
)
type RealEmailResponse struct {
Status string `json:"status"`
}
func main() {
email := "foo@bar.com"
url := "https://isitarealemail.com/api/email/validate?email=" + url.QueryEscape(email)
req, _ := http.NewRequest("GET", url, nil)
res, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Printf("error %v", err)
return
}
var myJson RealEmailResponse
json.Unmarshal(body, &myJson)
fmt.Printf("status for %v is %v", email, myJson.Status)
}

You will be able to test 100 emails per day, if you have more that that you will need to signup and get an API key. An email might be 'unknown' if the email server is unresponsive.

Using API Key

With an API key you will be able to test lots of emails each day.

package main
import (
"fmt"
"net/http"
"io/ioutil"
"encoding/json"
"net/url"
)
type RealEmailResponse struct {
Status string `json:"status"`
}
func main() {
email := "foo@bar.com"
apiKey := // todo login to get api key
url := "https://isitarealemail.com/api/email/validate?email=" + url.QueryEscape(email)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "bearer " + apiKey)
res, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Printf("error %v", err)
return
}
if res.StatusCode != 200 {
fmt.Printf("unexpected result, check your api key. %v", res.Status)
return
}
var myJson RealEmailResponse
json.Unmarshal(body, &myJson)
fmt.Printf("status for %v is %v", email, myJson.Status)
}

Bulk CSV file

Depending on your use case you may like to use the bulk csv file validation and read the csv file with go. You can validate a csv file full of emails addresses using the Real Email.

Get started with real email validations today.