KT100
KT100

Reputation: 1441

Extracting domain name from email in Python (including several special cases)

I am trying to extract just the domain name from email string, using Python. For a basic case such as [email protected], the following works well:

string.split("@")[1].rstrip(".com")   #would give me "xyz"

But I was hoping to find a solution that would get the domain name for cases such as:

One solution that comes to my mind is to use regular expression and strip off anything that follows the last dot but that still leaves special domains such as "xyz.co.sy" wherein I would expect to get just "xyz".

Upvotes: 2

Views: 12478

Answers (2)

Nikhil Katre
Nikhil Katre

Reputation: 2244

This would also work.

str.split("@")[1].split(".")[0]

Upvotes: 6

Pavan G jakati
Pavan G jakati

Reputation: 113

Below code should help you do the desired :

fromAddr = message.get('From').split('@')[1].rstrip('>')
        fromAddr = fromAddr.split(' ')[0]

Upvotes: 0

Related Questions