Tonight I need a little function that let me define a list of whitelisted email address and a list of blacklisted email address. This is then "merged" in a function called acceptOriginatorEmail(emailaddress) which is used to see if a particular email address is acceptable.

I've never written something like this before so I had to reinvent the wheel and guess my way towards a solution. My assumptions are that you start with whitelist and return True on a match on the blacklist, then you check against the blacklist and return False on a match and default to True if no match is made.

This makes it possible to define which email addresses should be accepted and which ones should be rejected like this:

whitelist = ('*', '')
blacklist = ('*')

Here's the code which does the crucial stuff:

def acceptOriginatorEmail(self, email, default_accept=True):
    """ return true if this email is either whitelisted or 
    not blacklisted """
    whitelist = self.getWhitelistEmails()
    blacklist = self.getBlacklistEmails()

    # note the order 
    for reject, emaillist in ([False, whitelist], [True, blacklist]):
        for okpattern in emaillist:
            if re.findall(okpattern.replace('*','\S+'), email, re.I):
                # match!
                if reject:
                    return False
                    return True

    # default is to accept all
    return default_accept

Download to see it in action.

What do you think people? Does it make any sense?

djo - 02 November 2005 [«« Reply to this]
Suggestion: this is a function for white/blacklisting strings - there's nothing email address-specific in here. I'd rename it to match the more general case.
Peter Bengtsson - 02 November 2005 [«« Reply to this]
Very good point. I was too simpleminded at that late hour. The function is extracted from a class which deals with email addresses and stuff so over there it made sense.
Sylvain Hellegouarch - 02 November 2005 [«« Reply to this]
Interesting but then it depends on you email adresses are entered to your system.

If one can enter whatever adress, what's the point? :)

I could have put into this comment email adress. How could you have prevented me from it?
Peter Bengtsson - 02 November 2005 [«« Reply to this]
The point? If you don't like the default behaviour set the default_accept parameter to False or look at my second example in the .py file.
djo - 02 November 2005 [«« Reply to this]
Peter - if you set default_accept to FALSE, do you need the blacklist at all any more?
Peter Bengtsson - 02 November 2005 [«« Reply to this]
Again a very good point. No, if you set default_accept to false, then the blacklist is useless.
Mohamed - 23 April 2006 [«« Reply to this]
may you Assist me Please

Your email will never ever be published