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 ir_values_obj = self.pool.get('ir.values')
284 vals['ref_ir_value'] = ir_values_obj.create(cr, uid, {
285 'name': _('Send Mail (%s)') % template_obj.name,
287 'key2': 'client_action_multi',
288 'value': "ir.actions.act_window," + str(vals['ref_ir_act_window']),
291 self.write(cr, uid, ids, {
292 'ref_ir_act_window': vals['ref_ir_act_window'],
293 'ref_ir_value': vals['ref_ir_value'],
297 def unlink_action(self, cr, uid, ids, context=None):
298 for template in self.browse(cr, uid, ids, context=context):
300 if template.ref_ir_act_window:
301 self.pool.get('ir.actions.act_window').unlink(cr, uid, template.ref_ir_act_window.id, context)
302 if template.ref_ir_value:
303 ir_values_obj = self.pool.get('ir.values')
304 ir_values_obj.unlink(cr, uid, template.ref_ir_value.id, context)
306 raise osv.except_osv(_("Warning"), _("Deletion of Record failed"))
308 def delete_action(self, cr, uid, ids, context=None):
309 self.unlink_action(cr, uid, ids, context=context)
312 def unlink(self, cr, uid, ids, context=None):
313 self.unlink_action(cr, uid, ids, context=context)
314 return super(email_template, self).unlink(cr, uid, ids, context=context)
316 def copy(self, cr, uid, id, default=None, context=None):
319 default = default.copy()
320 old = self.read(cr, uid, id, ['name'], context=context)
321 new_name = _("Copy of template %s") % old.get('name', 'No Name')
322 check = self.search(cr, uid, [('name', '=', new_name)], context=context)
324 new_name = new_name + '_' + random.choice('abcdefghij') + random.choice('lmnopqrs') + random.choice('tuvwzyz')
325 default.update({'name':new_name})
326 return super(email_template, self).copy(cr, uid, id, default, context)
328 def build_expression(self, field_name, sub_field_name, null_value, template_language='mako'):
330 Returns a template expression based on data provided
331 @param field_name: field name
332 @param sub_field_name: sub field name (M2O)
333 @param null_value: default value if the target value is empty
334 @param template_language: name of template engine
335 @return: computed expression
339 if template_language == 'mako':
341 expression = "${object." + field_name
343 expression += "." + sub_field_name
345 expression += " or '''%s'''" % null_value
347 elif template_language == 'django':
349 expression = "{{object." + field_name
351 expression += "." + sub_field_name
353 expression += "|default: '''%s'''" % null_value
357 def onchange_model_object_field(self, cr, uid, ids, model_object_field, template_language, context=None):
358 if not model_object_field:
361 field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
362 #Check if field is relational
363 if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
364 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
366 result['sub_object'] = res_ids[0]
367 result['copyvalue'] = self.build_expression(False,
371 result['sub_model_object_field'] = False
372 result['null_value'] = False
374 #Its a simple field... just compute placeholder
375 result['sub_object'] = False
376 result['copyvalue'] = self.build_expression(field_obj.name,
381 result['sub_model_object_field'] = False
382 result['null_value'] = False
383 return {'value':result}
385 def onchange_sub_model_object_field(self, cr, uid, ids, model_object_field, sub_model_object_field, template_language, context=None):
386 if not model_object_field or not sub_model_object_field:
389 field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
390 if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
391 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
392 sub_field_obj = self.pool.get('ir.model.fields').browse(cr, uid, sub_model_object_field, context)
394 result['sub_object'] = res_ids[0]
395 result['copyvalue'] = self.build_expression(field_obj.name,
400 result['sub_model_object_field'] = sub_model_object_field
401 result['null_value'] = False
403 #Its a simple field... just compute placeholder
404 result['sub_object'] = False
405 result['copyvalue'] = self.build_expression(field_obj.name,
410 result['sub_model_object_field'] = False
411 result['null_value'] = False
412 return {'value':result}
414 def onchange_null_value(self, cr, uid, ids, model_object_field, sub_model_object_field, null_value, template_language, context=None):
415 if not model_object_field and not null_value:
418 field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
419 if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
420 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
421 sub_field_obj = self.pool.get('ir.model.fields').browse(cr, uid, sub_model_object_field, context)
423 result['sub_object'] = res_ids[0]
424 result['copyvalue'] = self.build_expression(field_obj.name,
429 result['sub_model_object_field'] = sub_model_object_field
430 result['null_value'] = null_value
432 #Its a simple field... just compute placeholder
433 result['sub_object'] = False
434 result['copyvalue'] = self.build_expression(field_obj.name,
439 result['sub_model_object_field'] = False
440 result['null_value'] = null_value
441 return {'value':result}
443 def _add_attachment(self, cursor, user, mailbox_id, name, data, filename, context=None):
445 Add an attachment to a given mailbox entry.
447 :param data: base64 encoded attachment data to store
449 attachment_obj = self.pool.get('ir.attachment')
451 'name': (name or '') + _(' (Email Attachment)'),
453 'datas_fname': filename,
454 'description': name or _('No Description'),
455 'res_model':'email_template.mailbox',
456 'res_id': mailbox_id,
458 attachment_id = attachment_obj.create(cursor,
463 self.pool.get('email_template.mailbox').write(
468 'attachments_ids':[(4, attachment_id)],
469 'mail_type':'multipart/mixed'
473 def generate_attach_reports(self,
481 Generate report to be attached and attach it
482 to the email, and add any directly attached files as well.
484 @param cursor: Database Cursor
485 @param user: ID of User
486 @param template: Browse record of
488 @param record_id: ID of the target model
489 for which this mail has
491 @param mail: Browse record of email object
494 if template.report_template:
495 reportname = 'report.' + \
496 self.pool.get('ir.actions.report.xml').read(
499 template.report_template.id,
501 context)['report_name']
502 service = netsvc.LocalService(reportname)
504 data['model'] = template.model_int_name
505 (result, format) = service.create(cursor,
510 fname = tools.ustr(get_value(cursor, user, record_id,
511 template.file_name, template, context)
514 if not fname.endswith(ext):
516 self._add_attachment(cursor, user, mail.id, mail.subject, base64.b64encode(result), fname, context)
518 if template.attachment_ids:
519 for attachment in template.attachment_ids:
520 self._add_attachment(cursor, user, mail.id, attachment.name, attachment.datas, attachment.datas_fname, context)
524 def _generate_mailbox_item_from_template(self,
531 Generates an email from the template for
532 record record_id of target object
534 @param cursor: Database Cursor
535 @param user: ID of User
536 @param template: Browse record of
538 @param record_id: ID of the target model
539 for which this mail has
541 @return: ID of created object
545 #If account to send from is in context select it, else use enforced account
546 if 'account_id' in context.keys():
547 from_account = self.pool.get('email_template.account').read(
550 context.get('account_id'),
551 ['name', 'email_id'],
556 'id':template.from_account.id,
557 'name':template.from_account.name,
558 'email_id':template.from_account.email_id
560 lang = get_value(cursor,
568 ctx.update({'lang':lang})
569 template = self.browse(cursor, user, template.id, context=ctx)
571 # determine name of sender, either it is specified in email_id or we
572 # use the account name
573 email_id = from_account['email_id'].strip()
574 email_from = re.findall(r'([^ ,<@]+@[^> ,]+)', email_id)[0]
575 if email_from != email_id:
576 # we should keep it all, name is probably specified in the address
577 email_from = from_account['email_id']
579 email_from = tools.ustr(from_account['name']) + "<" + tools.ustr(email_id) + ">"
581 # FIXME: should do this in a loop and rename template fields to the corresponding
582 # mailbox fields. (makes no sense to have different names I think.
584 'email_from': email_from,
585 'email_to':get_value(cursor,
591 'email_cc':get_value(cursor,
597 'email_bcc':get_value(cursor,
603 'reply_to':get_value(cursor,
609 'subject':get_value(cursor,
612 template.def_subject,
615 'body_text':get_value(cursor,
618 template.def_body_text,
621 'body_html':get_value(cursor,
624 template.def_body_html,
627 'account_id' :from_account['id'],
628 #This is a mandatory field when automatic emails are sent
631 'mail_type':'multipart/alternative',
634 if template['message_id']:
635 # use provided message_id with placeholders
636 mailbox_values.update({'message_id': get_value(cursor, user, record_id, template['message_id'], template, context)})
638 elif template['track_campaign_item']:
639 # get appropriate message-id
640 mailbox_values.update({'message_id': tools.misc.generate_tracking_message_id(record_id)})
642 if not mailbox_values['account_id']:
643 raise Exception("Unable to send the mail. No account linked to the template.")
644 #Use signatures if allowed
645 if template.use_sign:
646 sign = self.pool.get('res.users').read(cursor,
650 context)['signature']
651 if mailbox_values['body_text']:
652 mailbox_values['body_text'] += sign
653 if mailbox_values['body_html']:
654 mailbox_values['body_html'] += sign
655 mailbox_id = self.pool.get('email_template.mailbox').create(
664 def generate_mail(self,
672 template = self.browse(cursor, user, template_id, context=context)
674 raise Exception("The requested template could not be loaded")
676 mailbox_obj = self.pool.get('email_template.mailbox')
677 for record_id in record_ids:
678 mailbox_id = self._generate_mailbox_item_from_template(
684 mail = mailbox_obj.browse(
690 if template.report_template or template.attachment_ids:
691 self.generate_attach_reports(
700 self.pool.get('email_template.mailbox').write(
707 # TODO : manage return value of all the records
708 result = self.pool.get('email_template.mailbox').send_this_mail(cursor, user, [mailbox_id], context)
714 ## FIXME: this class duplicates a lot of features of the email template send wizard,
715 ## one of the 2 should inherit from the other!
717 class email_template_preview(osv.osv_memory):
718 _name = "email_template.preview"
719 _description = "Email Template Preview"
721 def _get_model_recs(self, cr, uid, context=None):
724 #Fills up the selection box which allows records from the selected object to be displayed
725 self.context = context
726 if 'template_id' in context:
727 ref_obj_id = self.pool.get('email.template').read(cr, uid, context['template_id'], ['object_name'], context)
728 ref_obj_name = self.pool.get('ir.model').read(cr, uid, ref_obj_id['object_name'][0], ['model'], context)['model']
729 model_obj = self.pool.get(ref_obj_name)
730 ref_obj_ids = model_obj.search(cr, uid, [], 0, 20, 'id', context=context)
734 # also add the default one if requested, otherwise it won't be available for selection:
735 default_id = context.get('default_rel_model_ref')
736 if default_id and default_id not in ref_obj_ids:
737 ref_obj_ids.insert(0, default_id)
738 return model_obj.name_get(cr, uid, ref_obj_ids, context)
741 def default_get(self, cr, uid, fields, context=None):
744 result = super(email_template_preview, self).default_get(cr, uid, fields, context=context)
745 if (not fields or 'rel_model_ref' in fields) and 'template_id' in context \
746 and not result.get('rel_model_ref'):
747 selectables = self._get_model_recs(cr, uid, context=context)
748 result['rel_model_ref'] = selectables and selectables[0][0] or False
751 def _default_model(self, cursor, user, context=None):
753 Returns the default value for model field
754 @param cursor: Database Cursor
755 @param user: ID of current user
756 @param context: OpenERP Context
758 return self.pool.get('email.template').read(
761 context['template_id'],
763 context).get('object_name', False)
766 'ref_template':fields.many2one(
768 'Template', readonly=True),
769 'rel_model':fields.many2one('ir.model', 'Model', readonly=True),
770 'rel_model_ref':fields.selection(_get_model_recs, 'Referred Document'),
771 'to':fields.char('To', size=250, readonly=True),
772 'cc':fields.char('CC', size=250, readonly=True),
773 'bcc':fields.char('BCC', size=250, readonly=True),
774 'reply_to':fields.char('Reply-To',
776 help="The address recipients should reply to,"
777 " if different from the From address."
778 " Placeholders can be used here."),
779 'message_id':fields.char('Message-ID',
781 help="The Message-ID header value, if you need to"
782 "specify it, for example to automatically recognize the replies later."
783 " Placeholders can be used here."),
784 'subject':fields.char('Subject', size=200, readonly=True),
785 'body_text':fields.text('Body', readonly=True),
786 'body_html':fields.text('Body', readonly=True),
787 'report':fields.char('Report Name', size=100, readonly=True),
790 'ref_template': lambda self, cr, uid, ctx:ctx['template_id'] or False,
791 'rel_model': _default_model,
793 def on_change_ref(self, cr, uid, ids, rel_model_ref, context=None):
796 if not rel_model_ref:
800 context = self.context
801 template = self.pool.get('email.template').browse(cr, uid, context['template_id'], context)
802 #Search translated template
803 lang = get_value(cr, uid, rel_model_ref, template.lang, template, context)
806 ctx.update({'lang':lang})
807 template = self.pool.get('email.template').browse(cr, uid, context['template_id'], ctx)
808 vals['to'] = get_value(cr, uid, rel_model_ref, template.def_to, template, context)
809 vals['cc'] = get_value(cr, uid, rel_model_ref, template.def_cc, template, context)
810 vals['bcc'] = get_value(cr, uid, rel_model_ref, template.def_bcc, template, context)
811 vals['reply_to'] = get_value(cr, uid, rel_model_ref, template.reply_to, template, context)
812 if template.message_id:
813 vals['message_id'] = get_value(cr, uid, rel_model_ref, template.message_id, template, context)
814 elif template.track_campaign_item:
815 vals['message_id'] = tools.misc.generate_tracking_message_id(rel_model_ref)
816 vals['subject'] = get_value(cr, uid, rel_model_ref, template.def_subject, template, context)
817 vals['body_text'] = get_value(cr, uid, rel_model_ref, template.def_body_text, template, context)
818 vals['body_html'] = get_value(cr, uid, rel_model_ref, template.def_body_html, template, context)
819 vals['report'] = get_value(cr, uid, rel_model_ref, template.file_name, template, context)
820 return {'value':vals}
822 email_template_preview()
824 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: