1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2009 Sharoon Thomas
6 # Copyright (C) 2010-2010 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 ##############################################################################
31 from osv import osv, fields
32 from tools.translate import _
35 from mako.template import Template as MakoTemplate
36 TEMPLATE_ENGINES.append(('mako', 'Mako Templates'))
38 logging.getLogger('init').warning("module email_template: Mako templates not installed")
41 from django.template import Context, Template as DjangoTemplate
43 #http://code.google.com/p/django-tagging/issues/detail?id=110
44 from django.conf import settings
47 TEMPLATE_ENGINES.append(('django', 'Django Template'))
49 logging.getLogger('init').warning("module email_template: Django templates not installed")
55 def get_value(cursor, user, recid, message=None, template=None, context=None):
57 Evaluates an expression and returns its value
58 @param cursor: Database Cursor
59 @param user: ID of current user
60 @param recid: ID of the target record under evaluation
61 @param message: The expression to be evaluated
62 @param template: BrowseRecord object of the current template
63 @param context: OpenERP Context
64 @return: Computed message (unicode) or u""
66 pool = pooler.get_pool(cursor.dbname)
69 #Returns the computed expression
72 message = tools.ustr(message)
73 object = pool.get(template.model_int_name).browse(cursor, user, recid, context=context)
75 'user':pool.get('res.users').browse(cursor, user, user, context=context),
78 if template.template_language == 'mako':
79 templ = MakoTemplate(message, input_encoding='utf-8')
80 reply = MakoTemplate(message).render_unicode(object=object,
83 format_exceptions=True)
84 elif template.template_language == 'django':
85 templ = DjangoTemplate(message)
86 env['object'] = object
87 env['peobject'] = object
88 reply = templ.render(Context(env))
91 logging.exception("can't render %r", message)
96 class email_template(osv.osv):
97 "Templates for sending Email"
99 _name = "email.template"
100 _description = 'Email Templates for Models'
102 def change_model(self, cursor, user, ids, object_name, context=None):
104 mod_name = self.pool.get('ir.model').read(
108 ['model'], context)['model']
112 'value':{'model_int_name':mod_name}
116 'name' : fields.char('Name', size=100, required=True),
117 'object_name':fields.many2one('ir.model', 'Resource'),
118 'model_int_name':fields.char('Model Internal Name', size=200,),
119 'from_account':fields.many2one(
120 'email_template.account',
121 string="Email Account",
122 help="Emails will be sent from this approved account."),
123 'def_to':fields.char(
126 help="The Recipient of email. "
127 "Placeholders can be used here. "
128 "e.g. ${object.email_to}"),
129 'def_cc':fields.char(
132 help="Carbon Copy address(es), comma-separated."
133 " Placeholders can be used here. "
134 "e.g. ${object.email_cc}"),
135 'def_bcc':fields.char(
138 help="Blind Carbon Copy address(es), comma-separated."
139 " Placeholders can be used here. "
140 "e.g. ${object.email_bcc}"),
141 'reply_to':fields.char('Reply-To',
143 help="The address recipients should reply to,"
144 " if different from the From address."
145 " Placeholders can be used here. "
146 "e.g. ${object.email_reply_to}"),
147 'message_id':fields.char('Message-ID',
149 help="Specify the Message-ID SMTP header to use in outgoing emails. Please note that this overrides the Resource tracking option! Placeholders can be used here."),
150 'track_campaign_item':fields.boolean('Resource Tracking',
151 help="Enable this is you wish to include a special \
152 tracking marker in outgoing emails so you can identify replies and link \
153 them back to the corresponding resource record. \
154 This is useful for CRM leads for example"),
158 help="The default language for the email."
159 " Placeholders can be used here. "
160 "eg. ${object.partner_id.lang}"),
161 'def_subject':fields.char(
164 help="The subject of email."
165 " Placeholders can be used here.",
167 'def_body_text':fields.text(
168 'Standard Body (Text)',
169 help="The text version of the mail",
171 'def_body_html':fields.text(
172 'Body (Text-Web Client Only)',
173 help="The text version of the mail",
175 'use_sign':fields.boolean(
177 help="the signature from the User details"
178 " will be appended to the mail"),
179 'file_name':fields.char(
182 help="Name of the generated report file. Placeholders can be used in the filename. eg: 2009_SO003.pdf",
184 'report_template':fields.many2one(
185 'ir.actions.report.xml',
187 'attachment_ids': fields.many2many(
189 'email_template_attachment_rel',
193 help="You may attach existing files to this template, "
194 "so they will be added in all emails created from this template"),
195 'ref_ir_act_window':fields.many2one(
196 'ir.actions.act_window',
198 help="Action that will open this email template on Resource records",
200 'ref_ir_value':fields.many2one(
203 help="Button in the side bar of the form view of this Resource that will invoke the Window Action",
205 'allowed_groups':fields.many2many(
207 'template_group_rel',
208 'templ_id', 'group_id',
209 string="Allowed User Groups",
210 help="Only users from these groups will be"
211 " allowed to send mails from this Template"),
212 'model_object_field':fields.many2one(
215 help="Select the field from the model you want to use."
216 "\nIf it is a relationship field you will be able to "
217 "choose the nested values in the box below\n(Note:If "
218 "there are no values make sure you have selected the"
221 'sub_object':fields.many2one(
224 help='When a relation field is used this field'
225 ' will show you the type of field you have selected',
227 'sub_model_object_field':fields.many2one(
230 help="When you choose relationship fields "
231 "this field will specify the sub value you can use.",
233 'null_value':fields.char(
235 help="This Value is used if the field is empty",
236 size=50, store=False),
237 'copyvalue':fields.char(
240 help="Copy and paste the value in the "
241 "location you want to use a system value.",
243 'table_html':fields.text(
245 help="Copy this html code to your HTML message"
246 " body for displaying the info in your mail.",
248 #Template language(engine eg.Mako) specifics
249 'template_language':fields.selection(
251 'Templating Language',
257 'template_language' : lambda *a:'mako',
262 ('name', 'unique (name)','The template name must be unique !')
265 def create_action(self, cr, uid, ids, context=None):
269 template_obj = self.browse(cr, uid, ids, context=context)[0]
270 src_obj = template_obj.object_name.model
271 vals['ref_ir_act_window'] = self.pool.get('ir.actions.act_window').create(cr, uid, {
272 'name': template_obj.name,
273 'type': 'ir.actions.act_window',
274 'res_model': 'email_template.send.wizard',
275 'src_model': src_obj,
277 'context': "{'src_model':'%s','template_id':'%d','src_rec_id':active_id,'src_rec_ids':active_ids}" % (src_obj, template_obj.id),
278 'view_mode':'form,tree',
279 'view_id': self.pool.get('ir.ui.view').search(cr, uid, [('name', '=', 'email_template.send.wizard.form')], context=context)[0],
283 vals['ref_ir_value'] = self.pool.get('ir.values').create(cr, uid, {
284 'name': _('Send Mail (%s)') % template_obj.name,
286 'key2': 'client_action_multi',
287 'value': "ir.actions.act_window," + str(vals['ref_ir_act_window']),
290 self.write(cr, uid, ids, {
291 'ref_ir_act_window': vals['ref_ir_act_window'],
292 'ref_ir_value': vals['ref_ir_value'],
296 def unlink_action(self, cr, uid, ids, context=None):
297 for template in self.browse(cr, uid, ids, context=context):
299 if template.ref_ir_act_window:
300 self.pool.get('ir.actions.act_window').unlink(cr, uid, template.ref_ir_act_window.id, context)
301 if template.ref_ir_value:
302 self.pool.get('ir.values').unlink(cr, uid, template.ref_ir_value.id, context)
304 raise osv.except_osv(_("Warning"), _("Deletion of Record failed"))
306 def delete_action(self, cr, uid, ids, context=None):
307 self.unlink_action(cr, uid, ids, context=context)
310 def unlink(self, cr, uid, ids, context=None):
311 self.unlink_action(cr, uid, ids, context=context)
312 return super(email_template, self).unlink(cr, uid, ids, context=context)
314 def copy(self, cr, uid, id, default=None, context=None):
317 default = default.copy()
318 old = self.read(cr, uid, id, ['name'], context=context)
319 new_name = _("Copy of template ") + old.get('name', 'No Name')
320 check = self.search(cr, uid, [('name', '=', new_name)], context=context)
322 new_name = new_name + '_' + random.choice('abcdefghij') + random.choice('lmnopqrs') + random.choice('tuvwzyz')
323 default.update({'name':new_name})
324 return super(email_template, self).copy(cr, uid, id, default, context)
326 def build_expression(self, field_name, sub_field_name, null_value, template_language='mako'):
328 Returns a template expression based on data provided
329 @param field_name: field name
330 @param sub_field_name: sub field name (M2O)
331 @param null_value: default value if the target value is empty
332 @param template_language: name of template engine
333 @return: computed expression
337 if template_language == 'mako':
339 expression = "${object." + field_name
341 expression += "." + sub_field_name
343 expression += " or '''%s'''" % null_value
345 elif template_language == 'django':
347 expression = "{{object." + field_name
349 expression += "." + sub_field_name
351 expression += "|default: '''%s'''" % null_value
355 def onchange_model_object_field(self, cr, uid, ids, model_object_field, template_language, context=None):
356 if not model_object_field:
359 field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
360 #Check if field is relational
361 if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
362 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
364 result['sub_object'] = res_ids[0]
365 result['copyvalue'] = self.build_expression(False,
369 result['sub_model_object_field'] = False
370 result['null_value'] = False
372 #Its a simple field... just compute placeholder
373 result['sub_object'] = False
374 result['copyvalue'] = self.build_expression(field_obj.name,
379 result['sub_model_object_field'] = False
380 result['null_value'] = False
381 return {'value':result}
383 def onchange_sub_model_object_field(self, cr, uid, ids, model_object_field, sub_model_object_field, template_language, context=None):
384 if not model_object_field or not sub_model_object_field:
387 field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
388 if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
389 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
390 sub_field_obj = self.pool.get('ir.model.fields').browse(cr, uid, sub_model_object_field, context)
392 result['sub_object'] = res_ids[0]
393 result['copyvalue'] = self.build_expression(field_obj.name,
398 result['sub_model_object_field'] = sub_model_object_field
399 result['null_value'] = False
401 #Its a simple field... just compute placeholder
402 result['sub_object'] = False
403 result['copyvalue'] = self.build_expression(field_obj.name,
408 result['sub_model_object_field'] = False
409 result['null_value'] = False
410 return {'value':result}
412 def onchange_null_value(self, cr, uid, ids, model_object_field, sub_model_object_field, null_value, template_language, context=None):
413 if not model_object_field and not null_value:
416 field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
417 if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
418 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
419 sub_field_obj = self.pool.get('ir.model.fields').browse(cr, uid, sub_model_object_field, context)
421 result['sub_object'] = res_ids[0]
422 result['copyvalue'] = self.build_expression(field_obj.name,
427 result['sub_model_object_field'] = sub_model_object_field
428 result['null_value'] = null_value
430 #Its a simple field... just compute placeholder
431 result['sub_object'] = False
432 result['copyvalue'] = self.build_expression(field_obj.name,
437 result['sub_model_object_field'] = False
438 result['null_value'] = null_value
439 return {'value':result}
441 def _add_attachment(self, cursor, user, mailbox_id, name, data, filename, context=None):
443 Add an attachment to a given mailbox entry.
445 :param data: base64 encoded attachment data to store
447 attachment_obj = self.pool.get('ir.attachment')
449 'name': (name or '') + _(' (Email Attachment)'),
451 'datas_fname': filename,
452 'description': name or _('No Description'),
453 'res_model':'email_template.mailbox',
454 'res_id': mailbox_id,
456 attachment_id = attachment_obj.create(cursor,
461 self.pool.get('email_template.mailbox').write(
466 'attachments_ids':[(4, attachment_id)],
467 'mail_type':'multipart/mixed'
471 def generate_attach_reports(self,
479 Generate report to be attached and attach it
480 to the email, and add any directly attached files as well.
482 @param cursor: Database Cursor
483 @param user: ID of User
484 @param template: Browse record of
486 @param record_id: ID of the target model
487 for which this mail has
489 @param mail: Browse record of email object
492 if template.report_template:
493 reportname = 'report.' + \
494 self.pool.get('ir.actions.report.xml').read(
497 template.report_template.id,
499 context)['report_name']
500 service = netsvc.LocalService(reportname)
502 data['model'] = template.model_int_name
503 (result, format) = service.create(cursor,
508 fname = tools.ustr(get_value(cursor, user, record_id,
509 template.file_name, template, context)
512 if not fname.endswith(ext):
514 self._add_attachment(cursor, user, mail.id, mail.subject, base64.b64encode(result), fname, context)
516 if template.attachment_ids:
517 for attachment in template.attachment_ids:
518 self._add_attachment(cursor, user, mail.id, attachment.name, attachment.datas, attachment.datas_fname, context)
522 def _generate_mailbox_item_from_template(self,
529 Generates an email from the template for
530 record record_id of target object
532 @param cursor: Database Cursor
533 @param user: ID of User
534 @param template: Browse record of
536 @param record_id: ID of the target model
537 for which this mail has
539 @return: ID of created object
543 #If account to send from is in context select it, else use enforced account
544 if 'account_id' in context.keys():
545 from_account = self.pool.get('email_template.account').read(
548 context.get('account_id'),
549 ['name', 'email_id'],
554 'id':template.from_account.id,
555 'name':template.from_account.name,
556 'email_id':template.from_account.email_id
558 lang = get_value(cursor,
566 ctx.update({'lang':lang})
567 template = self.browse(cursor, user, template.id, context=ctx)
569 # determine name of sender, either it is specified in email_id or we
570 # use the account name
571 email_id = from_account['email_id'].strip()
572 email_from = re.findall(r'([^ ,<@]+@[^> ,]+)', email_id)[0]
573 if email_from != email_id:
574 # we should keep it all, name is probably specified in the address
575 email_from = from_account['email_id']
577 email_from = tools.ustr(from_account['name']) + "<" + tools.ustr('email_id') + ">",
579 # FIXME: should do this in a loop and rename template fields to the corresponding
580 # mailbox fields. (makes no sense to have different names I think.
582 'email_from': email_from,
583 'email_to':get_value(cursor,
589 'email_cc':get_value(cursor,
595 'email_bcc':get_value(cursor,
601 'reply_to':get_value(cursor,
607 'subject':get_value(cursor,
610 template.def_subject,
613 'body_text':get_value(cursor,
616 template.def_body_text,
619 'body_html':get_value(cursor,
622 template.def_body_html,
625 'account_id' :from_account['id'],
626 #This is a mandatory field when automatic emails are sent
629 'mail_type':'multipart/alternative',
632 if template['message_id']:
633 # use provided message_id with placeholders
634 mailbox_values.update({'message_id': get_value(cursor, user, record_id, template['message_id'], template, context)})
636 elif template['track_campaign_item']:
637 # get appropriate message-id
638 mailbox_values.update({'message_id': tools.misc.generate_tracking_message_id(record_id)})
640 if not mailbox_values['account_id']:
641 raise Exception("Unable to send the mail. No account linked to the template.")
642 #Use signatures if allowed
643 if template.use_sign:
644 sign = self.pool.get('res.users').read(cursor,
648 context)['signature']
649 if mailbox_values['body_text']:
650 mailbox_values['body_text'] += sign
651 if mailbox_values['body_html']:
652 mailbox_values['body_html'] += sign
653 mailbox_id = self.pool.get('email_template.mailbox').create(
662 def generate_mail(self,
670 template = self.browse(cursor, user, template_id, context=context)
672 raise Exception("The requested template could not be loaded")
674 mailbox_obj = self.pool.get('email_template.mailbox')
675 for record_id in record_ids:
676 mailbox_id = self._generate_mailbox_item_from_template(
682 mail = mailbox_obj.browse(
688 if template.report_template or template.attachment_ids:
689 self.generate_attach_reports(
698 self.pool.get('email_template.mailbox').write(
705 # TODO : manage return value of all the records
706 result = self.pool.get('email_template.mailbox').send_this_mail(cursor, user, [mailbox_id], context)
712 ## FIXME: this class duplicates a lot of features of the email template send wizard,
713 ## one of the 2 should inherit from the other!
715 class email_template_preview(osv.osv_memory):
716 _name = "email_template.preview"
717 _description = "Email Template Preview"
719 def _get_model_recs(self, cr, uid, context=None):
722 #Fills up the selection box which allows records from the selected object to be displayed
723 self.context = context
724 if 'template_id' in context:
725 ref_obj_id = self.pool.get('email.template').read(cr, uid, context['template_id'], ['object_name'], context)
726 ref_obj_name = self.pool.get('ir.model').read(cr, uid, ref_obj_id['object_name'][0], ['model'], context)['model']
727 model_obj = self.pool.get(ref_obj_name)
728 ref_obj_ids = model_obj.search(cr, uid, [], 0, 20, 'id', context=context)
732 # also add the default one if requested, otherwise it won't be available for selection:
733 default_id = context.get('default_rel_model_ref')
734 if default_id and default_id not in ref_obj_ids:
735 ref_obj_ids.insert(0, default_id)
736 return model_obj.name_get(cr, uid, ref_obj_ids, context)
739 def default_get(self, cr, uid, fields, context=None):
742 result = super(email_template_preview, self).default_get(cr, uid, fields, context=context)
743 if (not fields or 'rel_model_ref' in fields) and 'template_id' in context \
744 and not result.get('rel_model_ref'):
745 selectables = self._get_model_recs(cr, uid, context=context)
746 result['rel_model_ref'] = selectables and selectables[0][0] or False
749 def _default_model(self, cursor, user, context=None):
751 Returns the default value for model field
752 @param cursor: Database Cursor
753 @param user: ID of current user
754 @param context: OpenERP Context
756 return self.pool.get('email.template').read(
759 context['template_id'],
761 context).get('object_name', False)
764 'ref_template':fields.many2one(
766 'Template', readonly=True),
767 'rel_model':fields.many2one('ir.model', 'Model', readonly=True),
768 'rel_model_ref':fields.selection(_get_model_recs, 'Referred Document'),
769 'to':fields.char('To', size=250, readonly=True),
770 'cc':fields.char('CC', size=250, readonly=True),
771 'bcc':fields.char('BCC', size=250, readonly=True),
772 'reply_to':fields.char('Reply-To',
774 help="The address recipients should reply to,"
775 " if different from the From address."
776 " Placeholders can be used here."),
777 'message_id':fields.char('Message-ID',
779 help="The Message-ID header value, if you need to"
780 "specify it, for example to automatically recognize the replies later."
781 " Placeholders can be used here."),
782 'subject':fields.char('Subject', size=200, readonly=True),
783 'body_text':fields.text('Body', readonly=True),
784 'body_html':fields.text('Body', readonly=True),
785 'report':fields.char('Report Name', size=100, readonly=True),
788 'ref_template': lambda self, cr, uid, ctx:ctx['template_id'] or False,
789 'rel_model': _default_model,
791 def on_change_ref(self, cr, uid, ids, rel_model_ref, context=None):
794 if not rel_model_ref:
798 context = self.context
799 template = self.pool.get('email.template').browse(cr, uid, context['template_id'], context)
800 #Search translated template
801 lang = get_value(cr, uid, rel_model_ref, template.lang, template, context)
804 ctx.update({'lang':lang})
805 template = self.pool.get('email.template').browse(cr, uid, context['template_id'], ctx)
806 vals['to'] = get_value(cr, uid, rel_model_ref, template.def_to, template, context)
807 vals['cc'] = get_value(cr, uid, rel_model_ref, template.def_cc, template, context)
808 vals['bcc'] = get_value(cr, uid, rel_model_ref, template.def_bcc, template, context)
809 vals['reply_to'] = get_value(cr, uid, rel_model_ref, template.reply_to, template, context)
810 if template.message_id:
811 vals['message_id'] = get_value(cr, uid, rel_model_ref, template.message_id, template, context)
812 elif template.track_campaign_item:
813 vals['message_id'] = tools.misc.generate_tracking_message_id(rel_model_ref)
814 vals['subject'] = get_value(cr, uid, rel_model_ref, template.def_subject, template, context)
815 vals['body_text'] = get_value(cr, uid, rel_model_ref, template.def_body_text, template, context)
816 vals['body_html'] = get_value(cr, uid, rel_model_ref, template.def_body_html, template, context)
817 vals['report'] = get_value(cr, uid, rel_model_ref, template.file_name, template, context)
818 return {'value':vals}
820 email_template_preview()
822 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: