6

I'm having trouble pulling out the domain for emails. I've tried using variations of

u, _ := url.Parse(email) 

and other parsing from the standard library, but nothing that seems to parse: user@gmail.com into separate parts.

I've also tried net.SplitHostPort with no luck.

I don't want to get create a function which gets the len and separate to get substring after @ symbol if possible.

Does anyone have any ideas to do this?

Thanks!

jj1111
  • 607
  • 2
  • 10
  • 20
  • 1
    An email address is neither a url nor is it a host+port. Why not just split on the `@` character? – JimB Feb 15 '17 at 18:38
  • 1
    https://golang.org/pkg/net/mail/#example_ParseAddress – Mohamed Nuur Feb 15 '17 at 18:39
  • 1
    @MohamedNuur I saw this but am hoping to split e.Address in this example – jj1111 Feb 15 '17 at 18:56
  • @JimB can I split on @ and just get the remaining string? My plan now was get len of @ and do email[length:full_length] which would be several lines and I didn't want to do if there's a better solution – jj1111 Feb 15 '17 at 18:57
  • @jj1111 like @JimB said, just make your own function that splits by `@` character. I don't think there's any library out there for this as people don't normally parse the email. – Mohamed Nuur Feb 15 '17 at 18:58

1 Answers1

17

Here's an example I concocted from the golang documentation:

package main

import (
    "fmt"
    "strings"
)

func main() {
    email := "foo@bar.com"
    components := strings.Split(email, "@")
    username, domain := components[0], components[1]
    
    fmt.Printf("Username: %s, Domain: %s\n", username, domain)
}

UPDATE: 2020-09-01 - updating to use last @ sign per @Kevin's feedback in the comments.

package main

import (
    "fmt"
    "strings"
)

func main() {
    email := "foo@bar.com"
    at := strings.LastIndex(email, "@")
    if at >= 0 {
        username, domain := email[:at], email[at+1:]

        fmt.Printf("Username: %s, Domain: %s\n", username, domain)
    } else {
        fmt.Printf("Error: %s is an invalid email address\n", email)
    }
}

Here are some tests: https://play.golang.org/p/cg4RqZADLml

Mohamed Nuur
  • 5,536
  • 6
  • 39
  • 55
  • Nurr can you add links to the documentation you used? – Mike Graf Dec 26 '18 at 18:06
  • 3
    I highly doubt you will run into this in real life, but as written this answer is incorrect. The spec for valid email addresses permits multiple "@" signs in an email address. You want to use the last one as the domain part, not the first one. https://stackoverflow.com/a/12355882/329700 – Kevin Burke Oct 08 '19 at 00:02
  • Take a look into `net/mail` package it shows correct way to split email into parts – Dr.eel Aug 07 '20 at 16:32
  • Is `if at >= 0` consistent with the spec, seems it should be `if at > 0` as the username should be at least 1 character. Or is it possible just to have a `@blah.com` email address that lands all emails in a catch all? – Ali Aug 21 '23 at 07:52