Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

How can I extract the username and hostname/domain from e-mail addresses?

by Symuc (Novice)
on Nov 21, 2001 at 05:42 UTC ( [id://126701]=perlquestion: print w/replies, xml ) Need Help??

Symuc has asked for the wisdom of the Perl Monks concerning the following question:

I'm working on a mailing list, and I need to do username validation. So far, I have the entire message read into a variable, and I'm using an (admittedly poor) split() to get the "From:" header. I know that RFC822 allows email addresses to be in formats other than the user@domain, such as the following:
   John Doe <jdoe@domain.com>
   -or-
   "'Jane Smith'" <jsmith@otherdomain.com>

My question is this: How can I extract just the username and the hostname, preferably in separate variables? (And possibly, how can I use a regexp instead of the split() to extract the From: field?)
  • Comment on How can I extract the username and hostname/domain from e-mail addresses?

Replies are listed 'Best First'.
Re: How can I extract the username/domain?
by wog (Curate) on Nov 21, 2001 at 06:40 UTC
    The Mail::Address and Mail::Header modules can do this task:

    use Mail::Header; use Mail::Address; my $header = Mail::Header->new([@lines]); my($from) = Mail::Address->parse($header->get("From")); my($user,$host) = ($from->user(),$from->host());

    Edit by tye

      my $from = Mail::Address->parse($header->get("From"));
      should be
      my($from) = Mail::Address->parse($header->get("From"));
      (because Mail::Address->parse returns an array, and we don't want it's length.)
Re: How can I extract the username/domain?
by fuzzysteve (Beadle) on Nov 21, 2001 at 06:27 UTC
    /<(.+?)@(.+?)>/
    $1 should contain the user
    $2 should contain the domain

      $1 and $2 doesn't print anything. its ooutpu is blank. Pls provide me the full code.
      $1 and $2 not providing any output. it is giving blank output. My code is: $email = "old@oldone.com"; if ($email =~ /(^@+)@(.+)/) { #if ($email =~ /<(.+?)@(.+?)>/) { print "username is $1\n"; print "hostnmae is $2\n"; }
Re: How can I extract the username and hostname/domain from e-mail addresses?
by TomK32 (Monk) on Nov 22, 2001 at 00:54 UTC
    Don't forget to s/SPAM// due many started to add that against spammers
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://126701]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-04-26 00:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found