1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2009 Sharoon Thomas
6 # Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>
21 ##############################################################################
28 from osv import fields
30 from tools.translate import _
31 from tools.html_sanitize import html_sanitize
32 from tools import append_content_to_html
33 from urllib import quote as quote
34 _logger = logging.getLogger(__name__)
37 from mako.template import Template as MakoTemplate
39 _logger.warning("email_template: mako templates not available, templating features will not work!")
41 class email_template(osv.osv):
42 "Templates for sending email"
43 _name = "email.template"
44 _description = 'Email Templates'
46 def render_template(self, cr, uid, template, model, res_id, context=None):
47 """Render the given template text, replace mako expressions ``${expr}``
48 with the result of evaluating these expressions with
49 an evaluation context containing:
51 * ``user``: browse_record of the current user
52 * ``object``: browse_record of the document record this mail is
54 * ``context``: the context passed to the mail composition wizard
56 :param str template: the template text to render
57 :param str model: model name of the document record this mail is related to.
58 :param int res_id: id of the document record this mail is related to.
60 if not template: return u""
64 template = tools.ustr(template)
67 record = self.pool.get(model).browse(cr, uid, res_id, context=context)
68 user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
69 result = MakoTemplate(template).render_unicode(object=record,
71 # context kw would clash with mako internals
74 format_exceptions=True)
75 if result == u'False':
79 _logger.exception("failed to render mako template value %r", template)
82 def get_email_template(self, cr, uid, template_id=False, record_id=None, context=None):
87 template = self.browse(cr, uid, template_id, context)
88 lang = self.render_template(cr, uid, template.lang, template.model, record_id, context)
90 # Use translated template if necessary
93 template = self.browse(cr, uid, template.id, ctx)
95 template = self.browse(cr, uid, int(template_id), context)
98 def onchange_model_id(self, cr, uid, ids, model_id, context=None):
101 mod_name = self.pool.get('ir.model').browse(cr, uid, model_id, context).model
102 return {'value': {'model': mod_name}}
105 'name': fields.char('Name'),
106 'model_id': fields.many2one('ir.model', 'Applies to', help="The kind of document with with this template can be used"),
107 'model': fields.related('model_id', 'model', type='char', string='Related Document Model',
108 size=128, select=True, store=True, readonly=True),
109 'lang': fields.char('Language',
110 help="Optional translation language (ISO code) to select when sending out an email. "
111 "If not set, the english version will be used. "
112 "This should usually be a placeholder expression "
113 "that provides the appropriate language code, e.g. "
114 "${object.partner_id.lang.code}.",
115 placeholder="${object.partner_id.lang.code}"),
116 'user_signature': fields.boolean('Add Signature',
117 help="If checked, the user's signature will be appended to the text version "
119 'subject': fields.char('Subject', translate=True, help="Subject (placeholders may be used here)",),
120 'email_from': fields.char('From', help="Sender address (placeholders may be used here)"),
121 'email_to': fields.char('To', help="Comma-separated recipient addresses (placeholders may be used here)"),
122 'email_cc': fields.char('Cc', help="Carbon copy recipients (placeholders may be used here)"),
123 'reply_to': fields.char('Reply-To', help="Preferred response address (placeholders may be used here)"),
124 'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing Mail Server', readonly=False,
125 help="Optional preferred server for outgoing mails. If not set, the highest "
126 "priority one will be used."),
127 'body_html': fields.text('Body', translate=True, help="Rich-text/HTML version of the message (placeholders may be used here)"),
128 'report_name': fields.char('Report Filename', translate=True,
129 help="Name to use for the generated report file (may contain placeholders)\n"
130 "The extension can be omitted and will then come from the report type."),
131 'report_template': fields.many2one('ir.actions.report.xml', 'Optional report to print and attach'),
132 'ref_ir_act_window': fields.many2one('ir.actions.act_window', 'Sidebar action', readonly=True,
133 help="Sidebar action to make this template available on records "
134 "of the related document model"),
135 'ref_ir_value': fields.many2one('ir.values', 'Sidebar Button', readonly=True,
136 help="Sidebar button to open the sidebar action"),
137 'attachment_ids': fields.many2many('ir.attachment', 'email_template_attachment_rel', 'email_template_id',
138 'attachment_id', 'Attachments',
139 help="You may attach files to this template, to be added to all "
140 "emails created from this template"),
141 'auto_delete': fields.boolean('Auto Delete', help="Permanently delete this email after sending it, to save space"),
143 # Fake fields used to implement the placeholder assistant
144 'model_object_field': fields.many2one('ir.model.fields', string="Field",
145 help="Select target field from the related document model.\n"
146 "If it is a relationship field you will be able to select "
147 "a target field at the destination of the relationship."),
148 'sub_object': fields.many2one('ir.model', 'Sub-model', readonly=True,
149 help="When a relationship field is selected as first field, "
150 "this field shows the document model the relationship goes to."),
151 'sub_model_object_field': fields.many2one('ir.model.fields', 'Sub-field',
152 help="When a relationship field is selected as first field, "
153 "this field lets you select the target field within the "
154 "destination document model (sub-model)."),
155 'null_value': fields.char('Default Value', help="Optional value to use if the target field is empty"),
156 'copyvalue': fields.char('Placeholder Expression', help="Final placeholder expression, to be copy-pasted in the desired template field."),
163 def create_action(self, cr, uid, ids, context=None):
165 action_obj = self.pool.get('ir.actions.act_window')
166 data_obj = self.pool.get('ir.model.data')
167 for template in self.browse(cr, uid, ids, context=context):
168 src_obj = template.model_id.model
169 model_data_id = data_obj._get_id(cr, uid, 'mail', 'email_compose_message_wizard_form')
170 res_id = data_obj.browse(cr, uid, model_data_id, context=context).res_id
171 button_name = _('Send Mail (%s)') % template.name
172 vals['ref_ir_act_window'] = action_obj.create(cr, uid, {
174 'type': 'ir.actions.act_window',
175 'res_model': 'mail.compose.message',
176 'src_model': src_obj,
178 'context': "{'default_composition_mode': 'mass_mail', 'default_template_id' : %d}" % (template.id),
179 'view_mode':'form,tree',
184 vals['ref_ir_value'] = self.pool.get('ir.values').create(cr, uid, {
187 'key2': 'client_action_multi',
188 'value': "ir.actions.act_window," + str(vals['ref_ir_act_window']),
191 self.write(cr, uid, ids, {
192 'ref_ir_act_window': vals.get('ref_ir_act_window',False),
193 'ref_ir_value': vals.get('ref_ir_value',False),
197 def unlink_action(self, cr, uid, ids, context=None):
198 for template in self.browse(cr, uid, ids, context=context):
200 if template.ref_ir_act_window:
201 self.pool.get('ir.actions.act_window').unlink(cr, uid, template.ref_ir_act_window.id, context)
202 if template.ref_ir_value:
203 ir_values_obj = self.pool.get('ir.values')
204 ir_values_obj.unlink(cr, uid, template.ref_ir_value.id, context)
206 raise osv.except_osv(_("Warning"), _("Deletion of the action record failed."))
209 def unlink(self, cr, uid, ids, context=None):
210 self.unlink_action(cr, uid, ids, context=context)
211 return super(email_template, self).unlink(cr, uid, ids, context=context)
213 def copy(self, cr, uid, id, default=None, context=None):
214 template = self.browse(cr, uid, id, context=context)
217 default = default.copy()
218 default['name'] = template.name + _('(copy)')
219 return super(email_template, self).copy(cr, uid, id, default, context)
221 def build_expression(self, field_name, sub_field_name, null_value):
222 """Returns a placeholder expression for use in a template field,
223 based on the values provided in the placeholder assistant.
225 :param field_name: main field name
226 :param sub_field_name: sub field name (M2O)
227 :param null_value: default value if the target value is empty
228 :return: final placeholder expression
232 expression = "${object." + field_name
234 expression += "." + sub_field_name
236 expression += " or '''%s'''" % null_value
240 def onchange_sub_model_object_value_field(self, cr, uid, ids, model_object_field, sub_model_object_field=False, null_value=None, context=None):
244 'sub_model_object_field': False,
247 if model_object_field:
248 fields_obj = self.pool.get('ir.model.fields')
249 field_value = fields_obj.browse(cr, uid, model_object_field, context)
250 if field_value.ttype in ['many2one', 'one2many', 'many2many']:
251 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_value.relation)], context=context)
252 sub_field_value = False
253 if sub_model_object_field:
254 sub_field_value = fields_obj.browse(cr, uid, sub_model_object_field, context)
257 'sub_object': res_ids[0],
258 'copyvalue': self.build_expression(field_value.name, sub_field_value and sub_field_value.name or False, null_value or False),
259 'sub_model_object_field': sub_model_object_field or False,
260 'null_value': null_value or False
264 'copyvalue': self.build_expression(field_value.name, False, null_value or False),
265 'null_value': null_value or False
267 return {'value':result}
270 def generate_email(self, cr, uid, template_id, res_id, context=None):
271 """Generates an email from the template for given (model, res_id) pair.
273 :param template_id: id of the template to render.
274 :param res_id: id of the record to use for rendering the template (model
275 is taken from template definition)
276 :returns: a dict containing all relevant fields for creating a new
277 mail.mail entry, with one extra key ``attachments``, in the
278 format expected by :py:meth:`mail_thread.message_post`.
282 report_xml_pool = self.pool.get('ir.actions.report.xml')
283 template = self.get_email_template(cr, uid, template_id, res_id, context)
285 for field in ['subject', 'body_html', 'email_from',
286 'email_to', 'email_cc', 'reply_to']:
287 values[field] = self.render_template(cr, uid, getattr(template, field),
288 template.model, res_id, context=context) \
290 if template.user_signature:
291 signature = self.pool.get('res.users').browse(cr, uid, uid, context).signature
292 values['body_html'] = append_content_to_html(values['body_html'], signature)
294 if values['body_html']:
295 values['body'] = html_sanitize(values['body_html'])
297 values.update(mail_server_id=template.mail_server_id.id or False,
298 auto_delete=template.auto_delete,
299 model=template.model,
300 res_id=res_id or False)
303 # Add report in attachments
304 if template.report_template:
305 report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context)
306 report_service = 'report.' + report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name
307 # Ensure report is rendered using template's language
310 ctx['lang'] = self.render_template(cr, uid, template.lang, template.model, res_id, context)
311 service = netsvc.LocalService(report_service)
312 (result, format) = service.create(cr, uid, [res_id], {'model': template.model}, ctx)
313 result = base64.b64encode(result)
315 report_name = report_service
317 if not report_name.endswith(ext):
319 attachments.append(report_name, result)
321 # Add template attachments
322 for attach in template.attachment_ids:
323 attachments.append((attach.datas_fname, attach.datas))
325 values['attachments'] = attachments
328 def send_mail(self, cr, uid, template_id, res_id, force_send=False, context=None):
329 """Generates a new mail message for the given template and record,
330 and schedules it for delivery through the ``mail`` module's scheduler.
332 :param int template_id: id of the template to render
333 :param int res_id: id of the record to render the template with
334 (model is taken from the template)
335 :param bool force_send: if True, the generated mail.message is
336 immediately sent after being created, as if the scheduler
337 was executed for this message only.
338 :returns: id of the mail.message that was created
340 if context is None: context = {}
341 mail_mail = self.pool.get('mail.mail')
342 ir_attachment = self.pool.get('ir.attachment')
343 values = self.generate_email(cr, uid, template_id, res_id, context=context)
344 assert 'email_from' in values, 'email_from is missing or empty after template rendering, send_mail() cannot proceed'
345 attachments = values.pop('attachments') or {}
346 msg_id = mail_mail.create(cr, uid, values, context=context)
349 for fname, fcontent in attachments.iteritems():
352 'datas_fname': fname,
354 'res_model': mail_mail._name,
357 context.pop('default_type', None)
358 attachment_ids.append(ir_attachment.create(cr, uid, attachment_data, context=context))
360 mail_mail.write(cr, uid, msg_id, {'attachment_ids': [(6, 0, attachment_ids)]}, context=context)
362 mail_mail.send(cr, uid, [msg_id], context=context)
365 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: