tags:

views:

121

answers:

3

I need a Perl-compatible regular expression for filtering my email with smtp-gated. I only want to allow one domain ('mydomain.com') and reject everything else. How do I do this in a foolproof way? (regex_reject_mail_from)

I know this question halfway belongs on serverfault, but basically it's a Perl regex question so I think it fits stackoverflow more.

EDIT:

This should match so I can reject it:

"Someone" <[email protected]>

This should not match:

"Me" <[email protected]>

This shouldn't match also:

[email protected]

-

+3  A: 

I'd suggest the following:

\b[A-Z0-9._%+-]+@(?!mydomain\.com)[A-Z0-9.-]+\.[A-Z]{2,6}\b

Use the /i option to make it case-insensitive.

This will match most valid (and some invalid) e-mail addresses that don't have mydomain.com after the @. Keep in mind that e-mail validation is hard with regexes.

Tim Pietzcker
Shouldn't it be `mydomain\.com`?
Amarghosh
whats the rational behind `{2,6}`? Are sub-domain names limited to 6 chars?
Amarghosh
Oops, thanks for the correction. As for 6 chars, the longest TLD in use today is .museum - you could drop the 6, but that's not the only problem you'll run into if you try to validate e-mail addresses by regex.
Tim Pietzcker
Yeah, I know. I've heard about that one and only 5k char long regex :)
Amarghosh
+1  A: 
\b(?:"[ a-zA-Z]+")?\s*<?[a-zA-Z0-9_.]@(?!mydomain\.com)\w+(?:\.\w{2,})+>?\b

UPDATE: Note that this regex is fa{9,}r from being perfect. Check the official regex for email addresses for more info (Scroll down to the <p/> titled RFC 2822).

Amarghosh
+2  A: 

If your regex is going to be applied to the MAIL FROM line in the MTA communication then you do not need to concern yourself with the full 'email address' specification. MAIL FROM lines are just the email address enclosed in '<>', so any regex that tests for @mydomain.com> should work.

Jherico