Django Template Tag to protect the E-mail address

E-mail SecurityHere is a Django Template tag which you can use to protect the E-mail address on your website against bots or spiders that index or harvest E-mail addresses. It uses a substitution cipher with a different key for every page load.

This template tag encrypts the email address and generates a equivalent Javascript code that can decrypt it. This Javascript produce an email link when it runs on browser. As most bots and spider don’t executes Javascript they wouldn’t be able to extract mail addresses. While a visitor of your web page will not notice that you used this script as long as he/she has javascript enabled.

A normal visitor with a javascript enabled browser will find no difference. The visitor with non-javascript browser will see “[javascript protected email address]” in stead of the E-mail address.

Template Tag Code

class EncryptEmail(template.Node):
    def __init__(self, context_var):
        self.context_var = template.Variable(context_var)# context_var
    def render(self, context):
        import random
        email_address = self.context_var.resolve(context)
        character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'
        char_list = list(character_set)
        random.shuffle(char_list)
        
        key = ''.join(char_list)
        
        cipher_text = ''
        id = 'e' + str(random.randrange(1,999999999))

        for a in email_address:
            cipher_text += key[ character_set.find(a) ]
            
        script = 'var a="'+key+'";var b=a.split("").sort().join("");var c="'+cipher_text+'";var d="";'
        script += 'for(var e=0;e"+d+""'
        
        
        script = "eval(\""+ script.replace("\\","\\\\").replace('"','\\"') + "\")"
        script = ''
        
        return '[javascript protected email address]'+ script
        

def  encrypt_email(parser, token):
    """
        {% encrypt_email user.email %}
    """

    tokens = token.contents.split()
    if len(tokens)!=2:
        raise template.TemplateSyntaxError("%r tag accept two argument" % tokens[0])
    return EncryptEmail(tokens[1])

register.tag('encrypt_email', encrypt_email)

Usage

{% encrypt_email user.email %}

The javascript code it generates is something like this:

[javascript protected email address]


Demo

For demo visit :

Demo

Hope this template tag will help you to secure your e-mail addresses from bots and spider.

Lets have a spam free web.

9 Responses

  1. niks #

    thx mate… m looking for this kinda template tag for a long….

    Reply
  2. sepp #

    I can do that with one line of javascript :)

    Reply
    • nitin #

      please share your implementation with others as well.

      Reply
  3. Stephen #

    This is just what I’ve been looking for….just implemented it on one of my projects and it works like a charm. Thanks

    Reply

Leave a Reply