Get domain name from an email address
Asked Answered
L

4

59

I have an email address

[email protected]

I want to get the domain name from the email address. Can I achieve this with Regex?

Lankford answered 24/9, 2013 at 11:19 Comment(1)
if in doubt (or you haven't tried anything) use a RegEx! Now you have two problems.Abeyance
S
141

Using MailAddress you can fetch the Host from a property instead

MailAddress address = new MailAddress("[email protected]");
string host = address.Host; // host contains yahoo.com
Socrates answered 24/9, 2013 at 11:23 Comment(0)
A
29

If Default's answer is not what you're attempting you could always Split the email string after the '@'

string s = "[email protected]";
string[] words = s.Split('@');

words[0] would be xyz if you needed it in future
words[1] would be yahoo.com

But Default's answer is certainly an easier way of approaching this.

Adman answered 24/9, 2013 at 11:29 Comment(1)
Just as a heads up, email addresses can contain multiple "@". I'm pretty sure the last one will always separate the "user" from the "domain" though.Overelaborate
H
10

Or for string based solutions:

string address = "[email protected]";
string host;

// using Split
host = address.Split('@')[1];

// using Split with maximum number of substrings (more explicit)
host = address.Split(new char[] { '@' }, 2)[1];

// using Substring/IndexOf
host = address.Substring(address.IndexOf('@') + 1);
Hanley answered 24/9, 2013 at 11:29 Comment(0)
W
0

Simple Substring Method will do the trick here

string emailAddress = @"[email protected]"; string domainName = emailAddress.Substring(emailAddress.IndexOf('.',emailAddress.LastIndexOf('@')));

Console.WriteLine (domainName);

Or If you have have bit of money you can get this library and that will do the work for you

https://afterlogic.com/mailbee-net/docs/MailBee.Mime.EmailAddress.GetDomain.html

Wiesbaden answered 16/2, 2023 at 7:20 Comment(1)
I would add that, while MailBee.NET Objects is indeed a commercial product, some namespaces like MIME or HTML can be used at no cost.Chance

© 2022 - 2024 — McMap. All rights reserved.