[elspy] Useful function for catching recipients

A.M. Kuchling amk at amk.ca
Sun Feb 8 01:55:17 CET 2004

I've found the following function handy for checking if a given recipient is
present in the envelope-to.  Perhaps it's a candidate for the elspy library?

To reject all mail which is addressed to spamtrap at example.com.

    if match_recipients(info.recipients_list, 'spamtrap', 'example.com'):
	raise RejectMessage("Spam not wanted here")

To allow only 'barb' and 'amk' local parts:
    info.recipients_list = match_recipients(info.recipients_list, 
				['barb', 'amk'], 'example.com')


def match_recipients (recipient_list, local_parts, domains):
    """(str | [str], str | [str]) : [str]
    Checks whether the given recipient list contains any addresses
    that combine one of the local_parts with one of the domains.
    if isinstance(local_parts, str):
	local_parts = [local_parts]
    if isinstance(domains, str):
	domains = [domains]
    # Construct a regex pattern: (local1|local2)@(domain1|domain2)
    pattern = ('^(' + '|'.join(local_parts) + ')@(' +
               '|'.join(domains) + ')$')
    pattern = re.compile(pattern)
    matches = []
    for addr in recipient_list:
	if pattern.match(addr):

    return matches

More information about the elspy-users mailing list