skip to Main Content

I am building a website using Python Django and would like to display emails.

The emails are processed in the backend and are retrieved by ajax in JSON format.
How can I safely display the html body of an email without destroying my main theme?

I thought of implementing the email with iframes <iframe sandbox=""> . Are there other (better) ways to implement the html body without running into danger to compromise my website?

2

Answers


  1. Sanitize the HTML: Use a library like bleach in Django to sanitize and filter out potentially harmful HTML and JavaScript from the email’s HTML body. This way, you can ensure that only safe content is displayed. Here’s a basic example:

    import bleach
    
    email_html = "<p>Your email content here</p>"
    sanitized_html = bleach.clean(email_html, tags=['p', 'strong', 'em'], attributes={'p': ['style']})
    

    Customize the allowed tags and attributes according to your needs.

    Login or Signup to reply.
  2. You can use a library like bleach sanitize the HTML content before rendering it. This ensures that potentially malicious or unwanted content, such as JavaScript, is removed. After sanitizing the content, you can render it directly in your template.

    import bleach
    
    def sanitize_render_email_html(email_html):
        content = bleach.clean(email_html, tags=bleach.ALLOWED_TAGS, attributes=bleach.ALLOWED_ATTRIBUTES)
        return content
    

    Or use, DOMPurify for sanitization and then render the content in a HTML structure.

    import dompurify
    
    def sanitize_render_email_html(email_html):
        content = dompurify.sanitize(email_html)
        return content
    

    In your Django template:

    <div>
        {{ content | safe }}
    </div>
    

    Instead of iframes, you can display the email content in a modal or popover that overlays your main theme. This keeps the email content isolated from your main theme but provides a better user experience.

    You can use JavaScript libraries like Bootstrap’s modal or create a custom modal with CSS and JavaScript.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search