Email Addressing,Processing,and Handling

How do I see if an email address is valid?

In general,you can't.There are several methods available to see if it looks reasonable,but there is no way to determine if an address is actually deliverable without actually attempting delivery.

Using regular expressions:

  1. # Match basically blah@blah.blah
  2. if ( $addr =~ /^\S+\@\S+\.\S+$/ ) {
  3. print "Looks OK";
  4. }

If you're doing any real work, you may wish to look to one of the modules available on http://search.cpan.org, such as:

  • Email::Address
  • Email::Valid
  • Email::Valid makes it easy to determine if an email address is well-formed:
  1. use Email::Valid;
  2.  
  3. print ( Email::Valid->address( 'someone@gmail.com' ) ? 'Yes' : 'No' ); # prints Yes
  4. print ( Email::Valid->address( 'someone#gmail.com' ) ? 'Yes' : 'No' ); # prints No

Email::Valid can also tell you why an address is invalid:

  1. print "Invalid address: $Email::Valid::Details \n"
  2. unless Email::Valid->address( 'you#foo.bar' );

Want to contribute?

Submit a PR to github.com/petdance/perl101