Constantino Bene
Constantino Bene

Reputation: 41

Parse full email address included name

I need get domain from email address, problem is same email have name included name < email >, my curent code is :

var (
    ErrBadFormat        = errors.New("invalid format")
    emailRegexp = 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])?)*$")
)

func GetFromDomain(email string) string {
    if !emailRegexp.MatchString(email) {
        fmt.Println("Error %FROMDOMAIN ", email)
        return "localhost"
    }

    i := strings.LastIndexByte(email, '@')
    return email[i+1:]
}

What is the best practice to do this? My method with LastIndexByte return error when email have name included. How I can fix this problem?

Upvotes: 1

Views: 844

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79794

Your best bet is to use a proper email parsing library, such as the standard library's mail.ParseAddress method.

From there, you can easily extract the domain name from the address, by splitting on @--but be careful! It's actually legal to have a quoted or escaped @ in the username portion of the email address (i.e. "foo@bar"@example.com), so you must split on the last @.

Upvotes: 9

Related Questions