Email Obfuscator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import re
import random


email_link_pat = re.compile(r'<a\s+href=("|\')?mailto:[^>]+>[^<]*</a>')
email_pat = re.compile(r'\b[-.\w]+@[-.\w]+\.[a-z]{2,4}\b')


def get_script(m):
    code_list = []
    for c in m.group(0):
        d = ord(c)
        x = random.randint(0, d)
        code_list.append("%d+%d" % (x, d-x))

    return '<script type="text/javascript">document.write(String.fromCharCode(%s))</script>' % \
        ",".join(code_list)


class ObfuscateEmailAddressMiddleware(object):
    def process_response(self, request, response):
        if('text/html' in response['Content-Type']):
            response.content = email_link_pat.sub(get_script, response.content)
            response.content = email_pat.sub(get_script, response.content)
        return response

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.