mail_mail.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. import urlparse
  22. import werkzeug.urls
  23. import re
  24. from openerp.tools.translate import _
  25. from openerp import tools
  26. from openerp import SUPERUSER_ID
  27. from openerp.osv import osv, fields
  28. class MailMail(osv.Model):
  29. """Add the mass mailing campaign data to mail"""
  30. _name = 'mail.mail'
  31. _inherit = ['mail.mail']
  32. _columns = {
  33. 'mailing_id': fields.many2one('mail.mass_mailing', 'Mass Mailing'),
  34. 'statistics_ids': fields.one2many(
  35. 'mail.mail.statistics', 'mail_mail_id',
  36. string='Statistics',
  37. ),
  38. }
  39. def create(self, cr, uid, values, context=None):
  40. """ Override mail_mail creation to create an entry in mail.mail.statistics """
  41. # TDE note: should be after 'all values computed', to have values (FIXME after merging other branch holding create refactoring)
  42. mail_id = super(MailMail, self).create(cr, uid, values, context=context)
  43. if values.get('statistics_ids'):
  44. mail = self.browse(cr, SUPERUSER_ID, mail_id, context=context)
  45. for stat in mail.statistics_ids:
  46. self.pool['mail.mail.statistics'].write(cr, uid, [stat.id], {'message_id': mail.message_id}, context=context)
  47. return mail_id
  48. def _get_tracking_url(self, cr, uid, mail, partner=None, context=None):
  49. base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
  50. track_url = urlparse.urljoin(
  51. base_url, 'mail/track/%(mail_id)s/blank.gif?%(params)s' % {
  52. 'mail_id': mail.id,
  53. 'params': werkzeug.url_encode({'db': cr.dbname})
  54. }
  55. )
  56. return '<img src="%s" alt=""/>' % track_url
  57. def _get_unsubscribe_url(self, cr, uid, mail, email_to, msg=None, context=None):
  58. base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
  59. url = urlparse.urljoin(
  60. base_url, 'mail/mailing/%(mailing_id)s/unsubscribe?%(params)s' % {
  61. 'mailing_id': mail.mailing_id.id,
  62. 'params': werkzeug.url_encode({'db': cr.dbname, 'res_id': mail.res_id, 'email': email_to})
  63. }
  64. )
  65. return '<small><a href="%s">%s</a></small>' % (url, msg or _('Click to unsubscribe'))
  66. def send_get_mail_body(self, cr, uid, mail, partner=None, context=None):
  67. """ Override to add the tracking URL to the body. """
  68. body = super(MailMail, self).send_get_mail_body(cr, uid, mail, partner=partner, context=context)
  69. # prepend <base> tag for images using absolute urls
  70. domain = self.pool.get("ir.config_parameter").get_param(cr, uid, "web.base.url", context=context)
  71. base = "<base href='%s'>" % domain
  72. body = tools.append_content_to_html(base, body, plaintext=False, container_tag='div')
  73. # resolve relative image url to absolute for outlook.com
  74. def _sub_relative2absolute(match):
  75. return match.group(1) + urlparse.urljoin(domain, match.group(2))
  76. # Regex: https://regex101.com/r/aE8uG5/3
  77. body = re.sub('(<img(?=\s)[^>]*\ssrc=["\'])(/[^/][^"\']+)', _sub_relative2absolute, body)
  78. # Regex: https://regex101.com/r/kT3lD5/2
  79. body = re.sub(r'(<[^>]+\bstyle=["\'][^"\']+\burl\([\'"]?)(/[^/\'"][^\'")]+)', _sub_relative2absolute, body)
  80. # generate tracking URL
  81. if mail.statistics_ids:
  82. tracking_url = self._get_tracking_url(cr, uid, mail, partner, context=context)
  83. if tracking_url:
  84. body = tools.append_content_to_html(body, tracking_url, plaintext=False, container_tag='div')
  85. return body
  86. def send_get_email_dict(self, cr, uid, mail, partner=None, context=None):
  87. res = super(MailMail, self).send_get_email_dict(cr, uid, mail, partner, context=context)
  88. if mail.mailing_id and res.get('body') and res.get('email_to'):
  89. emails = tools.email_split(res.get('email_to')[0])
  90. email_to = emails and emails[0] or False
  91. unsubscribe_url = self._get_unsubscribe_url(cr, uid, mail, email_to, context=context)
  92. if unsubscribe_url:
  93. res['body'] = tools.append_content_to_html(res['body'], unsubscribe_url, plaintext=False, container_tag='p')
  94. return res
  95. def _postprocess_sent_message(self, cr, uid, mail, context=None, mail_sent=True):
  96. if mail_sent is True and mail.statistics_ids:
  97. self.pool['mail.mail.statistics'].write(cr, uid, [s.id for s in mail.statistics_ids], {'sent': fields.datetime.now()}, context=context)
  98. elif mail_sent is False and mail.statistics_ids:
  99. self.pool['mail.mail.statistics'].write(cr, uid, [s.id for s in mail.statistics_ids], {'exception': fields.datetime.now()}, context=context)
  100. return super(MailMail, self)._postprocess_sent_message(cr, uid, mail, context=context, mail_sent=mail_sent)