[FIX] mail: fixed bounce email recognition + invite email headers + mass mailing...
[odoo/odoo.git] / addons / mass_mailing / models / mail_mail.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>)
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
19 #
20 ##############################################################################
21
22 import urllib
23 import urlparse
24
25 from openerp import tools
26 from openerp import SUPERUSER_ID
27 from openerp.osv import osv, fields
28
29
30 class MailMail(osv.Model):
31     """Add the mass mailing campaign data to mail"""
32     _name = 'mail.mail'
33     _inherit = ['mail.mail']
34
35     _columns = {
36         'mailing_id': fields.many2one('mail.mass_mailing', 'Mass Mailing'),
37         'statistics_ids': fields.one2many(
38             'mail.mail.statistics', 'mail_mail_id',
39             string='Statistics',
40         ),
41     }
42
43     def create(self, cr, uid, values, context=None):
44         """ Override mail_mail creation to create an entry in mail.mail.statistics """
45         # TDE note: should be after 'all values computed', to have values (FIXME after merging other branch holding create refactoring)
46         mail_id = super(MailMail, self).create(cr, uid, values, context=context)
47         if values.get('statistics_ids'):
48             mail = self.browse(cr, SUPERUSER_ID, mail_id, context=context)
49             for stat in mail.statistics_ids:
50                 self.pool['mail.mail.statistics'].write(cr, uid, [stat.id], {'message_id': mail.message_id}, context=context)
51         return mail_id
52
53     def _get_tracking_url(self, cr, uid, mail, partner=None, context=None):
54         base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
55         track_url = urlparse.urljoin(
56             base_url, 'mail/track/%(mail_id)s/blank.gif?%(params)s' % {
57                 'mail_id': mail.id,
58                 'params': urllib.urlencode({'db': cr.dbname})
59             }
60         )
61         return '<img src="%s" alt=""/>' % track_url
62
63     def _get_unsubscribe_url(self, cr, uid, mail, email_to, msg=None, context=None):
64         base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
65         url = urlparse.urljoin(
66             base_url, 'mail/mailing/%(mailing_id)s/unsubscribe?%(params)s' % {
67                 'mailing_id': mail.mailing_id.id,
68                 'params': urllib.urlencode({'db': cr.dbname, 'res_id': mail.res_id, 'email': email_to})
69             }
70         )
71         return '<small><a href="%s">%s</a></small>' % (url, msg or 'Click to unsubscribe')
72
73     def send_get_mail_body(self, cr, uid, mail, partner=None, context=None):
74         """ Override to add the tracking URL to the body. """
75         body = super(MailMail, self).send_get_mail_body(cr, uid, mail, partner=partner, context=context)
76
77         # prepend <base> tag for images using absolute urls
78         domain = self.pool.get("ir.config_parameter").get_param(cr, uid, "web.base.url", context=context)
79         base = "<base href='%s'>" % domain
80         body = tools.append_content_to_html(base, body, plaintext=False, container_tag='div')
81
82         # generate tracking URL
83         if mail.statistics_ids:
84             tracking_url = self._get_tracking_url(cr, uid, mail, partner, context=context)
85             if tracking_url:
86                 body = tools.append_content_to_html(body, tracking_url, plaintext=False, container_tag='div')
87         return body
88
89     def send_get_email_dict(self, cr, uid, mail, partner=None, context=None):
90         res = super(MailMail, self).send_get_email_dict(cr, uid, mail, partner, context=context)
91         if mail.mailing_id and res.get('body') and res.get('email_to'):
92             emails = tools.email_split(res.get('email_to')[0])
93             email_to = emails and emails[0] or False
94             unsubscribe_url = self._get_unsubscribe_url(cr, uid, mail, email_to, context=context)
95             if unsubscribe_url:
96                 res['body'] = tools.append_content_to_html(res['body'], unsubscribe_url, plaintext=False, container_tag='p')
97         return res
98
99     def _postprocess_sent_message(self, cr, uid, mail, context=None, mail_sent=True):
100         if mail_sent is True and mail.statistics_ids:
101             self.pool['mail.mail.statistics'].write(cr, uid, [s.id for s in mail.statistics_ids], {'sent': fields.datetime.now()}, context=context)
102         elif mail_sent is False and mail.statistics_ids:
103             self.pool['mail.mail.statistics'].write(cr, uid, [s.id for s in mail.statistics_ids], {'exception': fields.datetime.now()}, context=context)
104         return super(MailMail, self)._postprocess_sent_message(cr, uid, mail, context=context, mail_sent=mail_sent)