sending.py 4.96 KB
Newer Older
Adrián Ribao's avatar
Adrián Ribao committed
1
# -*- coding: utf-8 -*-
Adrián Ribao's avatar
Adrián Ribao committed
2
import json
Adrián Ribao's avatar
Adrián Ribao committed
3
from StringIO import StringIO
Adrián Ribao's avatar
Adrián Ribao committed
4
5

import html2text
Adrián Ribao's avatar
Adrián Ribao committed
6
from django.conf import settings
Adrián Ribao's avatar
Adrián Ribao committed
7
from django.contrib.staticfiles.finders import find
Adrián Ribao's avatar
Adrián Ribao committed
8
from django.core.mail import EmailMultiAlternatives
Adrián Ribao's avatar
Adrián Ribao committed
9
10
11
from django.template import Template, Context
from lxml import etree
from premailer import Premailer
Adrián Ribao's avatar
Adrián Ribao committed
12
13
14
15
16
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.signing import Signer
from cartero.models import ShortURL, MailTracks
from django.contrib.sites.models import Site
Adrián Ribao's avatar
Adrián Ribao committed
17
18
19
20

class CampaignDeliver(object):
    def __init__(self, campaign):
        self.campaign = campaign
Adrián Ribao's avatar
Adrián Ribao committed
21
        self.site = Site.objects.get_current()
Adrián Ribao's avatar
Adrián Ribao committed
22

23
24
25
26
27
    def get_tree_from_html(self, html):
        parser = etree.HTMLParser()
        tree   = etree.parse(StringIO(html), parser)
        return tree

Adrián Ribao's avatar
Adrián Ribao committed
28
    def compile_css(self, tree):
Adrián Ribao's avatar
Adrián Ribao committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
        # Insert css from external files
        links = tree.xpath('//link')
        for link in links:
            href= link.attrib.get('href')
            if href:
                # Open that file
                rel_path = href.replace(settings.STATIC_URL, '')
                css_path = find(rel_path)
                with open(css_path, 'r') as f:
                    css = f.read()
                    css = css.replace('"', '\'')
                head = tree.find("head")
                style = etree.SubElement(head, "style")
                style.text = css
                # Remove the link
                head.remove(link)

        result = etree.tostring(tree.getroot(), pretty_print=True, method="html")
Adrián Ribao's avatar
Adrián Ribao committed
47
        #print result
Adrián Ribao's avatar
Adrián Ribao committed
48
49
50
51
52
        # CSS INLINER
        p = Premailer(result, remove_classes=False, include_star_selectors=True, strip_important=False)
        html = p.transform()
        return html

53
    def parse_links(self, tree):
Adrián Ribao's avatar
Adrián Ribao committed
54
55
56
57
58
59
60
61
62
        """
        Parse the links and return the lxml tree.
        """
        links = tree.xpath('//a')
        for link in links:
            href= link.attrib.get('href')
            if href and href.startswith('http'):
                short_url, created = ShortURL.objects.get_or_create(url=href)
                url = reverse('click_monitor', args=[short_url.code, self.campaign.id])
63
                fqdn_url = 'http://{0}{1}'.format(self.site.domain, url)
Adrián Ribao's avatar
Adrián Ribao committed
64
65
66
67
68
69
70
71
72
                link.attrib['href'] = fqdn_url
        return tree

    def add_track(self, tree, contact):
        body = tree.find("body")
        img = etree.SubElement(body, "img")
        mail_track = MailTracks(campaign=self.campaign, contact=contact)
        mail_track.save()
        url = reverse('track', args=[mail_track.id,])
73
        fqdn_image_url = 'http://{0}{1}'.format(self.site.domain, url)
Adrián Ribao's avatar
Adrián Ribao committed
74
75
76
        img.attrib['src'] = fqdn_image_url
        return tree

Adrián Ribao's avatar
Adrián Ribao committed
77
78
79
80
81
82
83
84
    def convert_email_to_text(self, html):
        h = html2text.HTML2Text()
        #h.ignore_links = True
        #h.inline_links = True
        text = h.handle(html)
        return text

    def send_to_contact(self, contact):
Adrián Ribao's avatar
Adrián Ribao committed
85
        msg = self.compose_email(contact)
Adrián Ribao's avatar
Adrián Ribao committed
86
87
        msg.send()

Adrián Ribao's avatar
Adrián Ribao committed
88
    def compose_email(self, contact):
Adrián Ribao's avatar
Adrián Ribao committed
89
        html = self.campaign.email_template.html
Adrián Ribao's avatar
Adrián Ribao committed
90
91
92
93

        signer = Signer()
        sign = signer.sign(contact.email)
        unsubscribe_url = reverse('unsubscribe', args=[sign,])
Adrián Ribao's avatar
Adrián Ribao committed
94
95
96
97
98
99

        context = {
                'first_name': contact.first_name,
                'last_name': contact.last_name,
                'email': contact.email,
                'site': contact.site,
100
                'unsubscribe_url': 'http://{0}{1}'.format(contact.site.domain, unsubscribe_url),
Adrián Ribao's avatar
Adrián Ribao committed
101
102
103
104
105
                }
        if contact.data:
            data = json.loads(contact.data)
            context.update(data)

Adrián Ribao's avatar
Adrián Ribao committed
106
107
108
        t = Template(html)
        html = t.render(Context(context))

109
110
        # Get the tree
        tree = self.get_tree_from_html(html)
Adrián Ribao's avatar
Adrián Ribao committed
111
        # Parse links
112
        tree = self.parse_links(tree)
Adrián Ribao's avatar
Adrián Ribao committed
113
114
115
116
        # Add track
        tree = self.add_track(tree, contact)
        # Compile css
        final_html = self.compile_css(tree)
Adrián Ribao's avatar
Adrián Ribao committed
117
118

        text_content = self.convert_email_to_text(final_html)
Adrián Ribao's avatar
Adrián Ribao committed
119

Adrián Ribao's avatar
Adrián Ribao committed
120
121
122
        reply_to = self.campaign.reply_to or settings.DEFAULT_FROM_EMAIL
        from_email = self.campaign.from_email or settings.DEFAULT_FROM_EMAIL

Adrián Ribao's avatar
Adrián Ribao committed
123
124
125
        msg = EmailMultiAlternatives(
                subject=self.campaign.subject,
                body=text_content,
Adrián Ribao's avatar
Adrián Ribao committed
126
127
128
129
130
131
                to=[contact.email, ],
                from_email=from_email,
                headers = {
                    'Reply-To': reply_to
                    }
                )
Adrián Ribao's avatar
Adrián Ribao committed
132
        msg.attach_alternative(final_html, "text/html")
Adrián Ribao's avatar
Adrián Ribao committed
133
134
135

        return msg

Adrián Ribao's avatar
Adrián Ribao committed
136
137
138
139
140
141
142
143
144
145
146
    def get_contacts(self, testing=False):
        contacts = self.campaign.contacts.all()
        if testing:
            contacts = contacts.filter(testing=True)
        return contacts

    def send_test(self):
        contacts = self.get_contacts(testing=True)
        for contact in contacts:
            self.send_to_contact(contact)

Adrián Ribao's avatar
Adrián Ribao committed
147
    def send(self):
Adrián Ribao's avatar
Adrián Ribao committed
148
        contacts = self.get_contacts()
Adrián Ribao's avatar
Adrián Ribao committed
149
150
        for contact in contacts:
            self.send_to_contact(contact)