summaryrefslogtreecommitdiff
path: root/addons/email_template
diff options
context:
space:
mode:
authorStephane Wirtel <stw@openerp.com>2011-09-13 16:00:16 +0200
committerStephane Wirtel <stw@openerp.com>2011-09-13 16:00:16 +0200
commit2a59ce92e3ea35cca00a314d44556b522b3c2fa8 (patch)
tree6e7eec2157a513284e6740a95f2e39b7f04aef79 /addons/email_template
parent8a2bc42c3c45b4d3c94070a29fa76636256f3da7 (diff)
parent2a40f9a4997eecc6f997ab0e43dc6334263b9cad (diff)
[MERGE] Email Framework - lp:~openerp-dev/openobject-addons/trunk-emails-unified
bzr revid: stw@openerp.com-20110913140016-zzfynrnjdaap0tfb
Diffstat (limited to 'addons/email_template')
-rw-r--r--addons/email_template/__init__.py6
-rw-r--r--addons/email_template/__openerp__.py51
-rw-r--r--addons/email_template/email_template.py1042
-rw-r--r--addons/email_template/email_template_account.py470
-rw-r--r--addons/email_template/email_template_account_view.xml124
-rw-r--r--addons/email_template/email_template_mailbox.py214
-rw-r--r--addons/email_template/email_template_mailbox_view.xml134
-rw-r--r--addons/email_template/email_template_scheduler_data.xml16
-rw-r--r--addons/email_template/email_template_view.xml180
-rw-r--r--addons/email_template/email_template_workflow.xml64
-rw-r--r--addons/email_template/security/email_template_security.xml6
-rw-r--r--addons/email_template/security/ir.model.access.csv10
-rw-r--r--addons/email_template/wizard/__init__.py5
-rw-r--r--addons/email_template/wizard/email_compose_message_view.xml30
-rw-r--r--addons/email_template/wizard/email_template_preview.py93
-rw-r--r--addons/email_template/wizard/email_template_preview_view.xml53
-rw-r--r--addons/email_template/wizard/email_template_send_wizard.py279
-rw-r--r--addons/email_template/wizard/email_template_send_wizard_view.xml63
-rw-r--r--addons/email_template/wizard/mail_compose_message.py156
19 files changed, 738 insertions, 2258 deletions
diff --git a/addons/email_template/__init__.py b/addons/email_template/__init__.py
index dd87232679d..97931ea8bd5 100644
--- a/addons/email_template/__init__.py
+++ b/addons/email_template/__init__.py
@@ -3,7 +3,7 @@
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2009 Sharoon Thomas
-# Copyright (C) 2010-2010 OpenERP SA (<http://www.openerp.com>)
+# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -19,9 +19,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
##############################################################################
-
-import email_template_account
import email_template
-import email_template_mailbox
import wizard
+# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diff --git a/addons/email_template/__openerp__.py b/addons/email_template/__openerp__.py
index f56062f37ed..e5f83f9ac0c 100644
--- a/addons/email_template/__openerp__.py
+++ b/addons/email_template/__openerp__.py
@@ -3,7 +3,7 @@
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2009 Sharoon Thomas
-# Copyright (C) 2010-2010 OpenERP SA (<http://www.openerp.com>)
+# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -21,32 +21,47 @@
##############################################################################
{
- "name" : "Email Template for OpenERP",
- "version" : "0.7 RC",
+ "name" : "Email Templates",
+ "version" : "1.1",
"author" : "Openlabs",
"website" : "http://openerp.com",
"category" : "Tools",
'complexity': "expert",
- "depends" : ['marketing', 'base_tools'],
+ "depends" : ['mail'],
"description": """
-Email Template is extraction of Power Email basically just to send emails.
-==========================================================================
+Email Templating (simplified version of the original Power Email by Openlabs)
+=============================================================================
-You can define email accounts(server, port, mail format - HTML/Text/Both)
-and email templates (resource, recipient, subject, body, attachments).
+Lets you design complete email templates related to any OpenERP document (Sale
+Orders, Invoices and so on), including sender, recipient, subject, body (HTML and
+Text). You may also automatically attach files to your templates, or print and
+attach a report.
+
+For advanced use, the templates may include dynamic attributes of the document
+they are related to. For example, you may use the name of a Partner's country
+when writing to them, also providing a safe default in case the attribute is
+not defined. Each template contains a built-in assistant to help with the
+inclusion of these dynamic values.
+
+If you enable the option, a composition assistant will also appear in the sidebar
+of the OpenERP documents to which the template applies (e.g. Invoices).
+This serves as a quick way to send a new email based on the template, after
+reviewing and adapting the contents, if needed.
+This composition assistant will also turn into a mass mailing system when called
+for multiple documents at once.
+
+These email templates are also at the heart of the marketing campaign system
+(see the ``marketing_campaign`` application), if you need to automate larger
+campaigns on any OpenERP document.
+
+Technical note: only the templating system of the original Power Email by
+Openlabs was kept
-For each email template, you can have OpenERP generate a Wizard Action / Button
-that will be related to the object. So if you choose to do marketing campaigns
-for leads, the action will be added to the right side panel of the Lead form.
""",
- "init_xml": ['email_template_scheduler_data.xml'],
- "update_xml": [
- 'security/email_template_security.xml',
- 'email_template_workflow.xml',
- 'email_template_account_view.xml',
+ "data": [
+ 'wizard/email_template_preview_view.xml',
'email_template_view.xml',
- 'email_template_mailbox_view.xml',
- 'wizard/email_template_send_wizard_view.xml',
+ 'wizard/email_compose_message_view.xml',
'security/ir.model.access.csv'
],
"installable": True,
diff --git a/addons/email_template/email_template.py b/addons/email_template/email_template.py
index aabc211df11..3917b3f2ddb 100644
--- a/addons/email_template/email_template.py
+++ b/addons/email_template/email_template.py
@@ -3,7 +3,7 @@
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2009 Sharoon Thomas
-# Copyright (C) 2010-2010 OpenERP SA (<http://www.openerp.com>)
+# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -21,277 +21,186 @@
##############################################################################
import base64
-import random
-import netsvc
import logging
-import re
-
-TEMPLATE_ENGINES = []
-from osv import osv, fields
+import netsvc
+from osv import osv
+from osv import fields
+import tools
from tools.translate import _
try:
from mako.template import Template as MakoTemplate
- TEMPLATE_ENGINES.append(('mako', 'Mako Templates'))
except ImportError:
- logging.getLogger('init').warning("module email_template: Mako templates not installed")
-
-try:
- from django.template import Context, Template as DjangoTemplate
- #Workaround for bug:
- #http://code.google.com/p/django-tagging/issues/detail?id=110
- from django.conf import settings
- settings.configure()
- #Workaround ends
- TEMPLATE_ENGINES.append(('django', 'Django Template'))
-except ImportError:
- logging.getLogger('init').warning("module email_template: Django templates not installed")
-
-import tools
-import pooler
-import logging
+ logging.getLogger('init').warning("email_template: mako templates not available, templating features will not work!")
-def get_value(cursor, user, recid, message=None, template=None, context=None):
- """
- Evaluates an expression and returns its value
- @param cursor: Database Cursor
- @param user: ID of current user
- @param recid: ID of the target record under evaluation
- @param message: The expression to be evaluated
- @param template: BrowseRecord object of the current template
- @param context: OpenERP Context
- @return: Computed message (unicode) or u""
- """
- pool = pooler.get_pool(cursor.dbname)
- if message is None:
- message = {}
- #Returns the computed expression
- if message:
+class email_template(osv.osv):
+ "Templates for sending email"
+ _inherit = 'mail.message'
+ _name = "email.template"
+ _description = 'Email Templates'
+ _rec_name = 'name' # override mail.message's behavior
+
+ def render_template(self, cr, uid, template, model, res_id, context=None):
+ """Render the given template text, replace mako expressions ``${expr}``
+ with the result of evaluating these expressions with
+ an evaluation context containing:
+
+ * ``user``: browse_record of the current user
+ * ``object``: browse_record of the document record this mail is
+ related to
+ * ``context``: the context passed to the mail composition wizard
+
+ :param str template: the template text to render
+ :param str model: model name of the document record this mail is related to.
+ :param int res_id: id of the document record this mail is related to.
+ """
+ if not template: return u""
try:
- message = tools.ustr(message)
- object = pool.get(template.model_int_name).browse(cursor, user, recid, context=context)
- env = {
- 'user':pool.get('res.users').browse(cursor, user, user, context=context),
- 'db':cursor.dbname
- }
- if template.template_language == 'mako':
- templ = MakoTemplate(message, input_encoding='utf-8')
- reply = MakoTemplate(message).render_unicode(object=object,
- peobject=object,
- env=env,
- format_exceptions=True)
- elif template.template_language == 'django':
- templ = DjangoTemplate(message)
- env['object'] = object
- env['peobject'] = object
- reply = templ.render(Context(env))
- return reply or False
+ template = tools.ustr(template)
+ record = None
+ if res_id:
+ record = self.pool.get(model).browse(cr, uid, res_id, context=context)
+ user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
+ result = MakoTemplate(template).render_unicode(object=record,
+ user=user,
+ # context kw would clash with mako internals
+ ctx=context,
+ format_exceptions=True)
+ if result == u'False':
+ result = u''
+ return result
except Exception:
- logging.exception("can't render %r", message)
+ logging.exception("failed to render mako template value %r", template)
return u""
- else:
- return message
-class email_template(osv.osv):
- "Templates for sending Email"
-
- _name = "email.template"
- _description = 'Email Templates for Models'
-
- def change_model(self, cursor, user, ids, object_name, context=None):
- if object_name:
- mod_name = self.pool.get('ir.model').read(
- cursor,
- user,
- object_name,
- ['model'], context)['model']
+ def get_email_template(self, cr, uid, template_id=False, record_id=None, context=None):
+ if context is None:
+ context = {}
+ if not template_id:
+ return False
+ template = self.browse(cr, uid, template_id, context)
+ lang = self.render_template(cr, uid, template.lang, template.model, record_id, context)
+ if lang:
+ # Use translated template if necessary
+ ctx = context.copy()
+ ctx['lang'] = lang
+ template = self.browse(cr, uid, template.id, ctx)
else:
- mod_name = False
- return {
- 'value':{'model_int_name':mod_name}
- }
+ template = self.browse(cr, uid, int(template_id), context)
+ return template
+
+ def onchange_model_id(self, cr, uid, ids, model_id, context=None):
+ mod_name = False
+ if model_id:
+ mod_name = self.pool.get('ir.model').browse(cr, uid, model_id, context).model
+ return {'value':{'model': mod_name}}
_columns = {
- 'name' : fields.char('Name', size=100, required=True),
- 'object_name':fields.many2one('ir.model', 'Resource'),
- 'model_int_name':fields.char('Model Internal Name', size=200,),
- 'from_account':fields.many2one(
- 'email_template.account',
- string="Email Account",
- help="Emails will be sent from this approved account."),
- 'def_to':fields.char(
- 'Recipient (To)',
- size=250,
- help="The Recipient of email. "
- "Placeholders can be used here. "
- "e.g. ${object.email_to}"),
- 'def_cc':fields.char(
- 'CC',
- size=250,
- help="Carbon Copy address(es), comma-separated."
- " Placeholders can be used here. "
- "e.g. ${object.email_cc}"),
- 'def_bcc':fields.char(
- 'BCC',
- size=250,
- help="Blind Carbon Copy address(es), comma-separated."
- " Placeholders can be used here. "
- "e.g. ${object.email_bcc}"),
- 'reply_to':fields.char('Reply-To',
- size=250,
- help="The address recipients should reply to,"
- " if different from the From address."
- " Placeholders can be used here. "
- "e.g. ${object.email_reply_to}"),
- 'message_id':fields.char('Message-ID',
- size=250,
- 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."),
- 'track_campaign_item':fields.boolean('Resource Tracking',
- help="Enable this is you wish to include a special \
-tracking marker in outgoing emails so you can identify replies and link \
-them back to the corresponding resource record. \
-This is useful for CRM leads for example"),
- 'lang':fields.char(
- 'Language',
- size=250,
- help="The default language for the email."
- " Placeholders can be used here. "
- "eg. ${object.partner_id.lang}"),
- 'def_subject':fields.char(
- 'Subject',
- size=200,
- help="The subject of email."
- " Placeholders can be used here.",
- translate=True),
- 'def_body_text':fields.text(
- 'Standard Body (Text)',
- help="The text version of the mail",
- translate=True),
- 'def_body_html':fields.text(
- 'Body (Text-Web Client Only)',
- help="The text version of the mail",
- translate=True),
- 'use_sign':fields.boolean(
- 'Signature',
- help="the signature from the User details"
- " will be appended to the mail"),
- 'file_name':fields.char(
- 'Report Filename',
- size=200,
- help="Name of the generated report file. Placeholders can be used in the filename. eg: 2009_SO003.pdf",
- translate=True),
- 'report_template':fields.many2one(
- 'ir.actions.report.xml',
- 'Report to send'),
- 'attachment_ids': fields.many2many(
- 'ir.attachment',
- 'email_template_attachment_rel',
- 'email_template_id',
- 'attachment_id',
- 'Attached Files',
- help="You may attach existing files to this template, "
- "so they will be added in all emails created from this template"),
- 'ref_ir_act_window':fields.many2one(
- 'ir.actions.act_window',
- 'Window Action',
- help="Action that will open this email template on Resource records",
- readonly=True),
- 'ref_ir_value':fields.many2one(
- 'ir.values',
- 'Wizard Button',
- help="Button in the side bar of the form view of this Resource that will invoke the Window Action",
- readonly=True),
- 'allowed_groups':fields.many2many(
- 'res.groups',
- 'template_group_rel',
- 'templ_id', 'group_id',
- string="Allowed User Groups",
- help="Only users from these groups will be"
- " allowed to send mails from this Template"),
- 'model_object_field':fields.many2one(
- 'ir.model.fields',
- string="Field",
- help="Select the field from the model you want to use."
- "\nIf it is a relationship field you will be able to "
- "choose the nested values in the box below\n(Note:If "
- "there are no values make sure you have selected the"
- " correct model)",
- store=False),
- 'sub_object':fields.many2one(
- 'ir.model',
- 'Sub-model',
- help='When a relation field is used this field'
- ' will show you the type of field you have selected',
- store=False),
- 'sub_model_object_field':fields.many2one(
- 'ir.model.fields',
- 'Sub Field',
- help="When you choose relationship fields "
- "this field will specify the sub value you can use.",
- store=False),
- 'null_value':fields.char(
- 'Null Value',
- help="This Value is used if the field is empty",
- size=50, store=False),
- 'copyvalue':fields.char(
- 'Expression',
- size=100,
- help="Copy and paste the value in the "
- "location you want to use a system value.",
- store=False),
- 'table_html':fields.text(
- 'HTML code',
- help="Copy this html code to your HTML message"
- " body for displaying the info in your mail.",
- store=False),
- #Template language(engine eg.Mako) specifics
- 'template_language':fields.selection(
- TEMPLATE_ENGINES,
- 'Templating Language',
- required=True
- )
+ 'name': fields.char('Name', size=250),
+ 'model_id': fields.many2one('ir.model', 'Related document model'),
+ 'lang': fields.char('Language Selection', size=250,
+ help="Optional translation language (ISO code) to select when sending out an email. "
+ "If not set, the english version will be used. "
+ "This should usually be a placeholder expression "
+ "that provides the appropriate language code, e.g. "
+ "${object.partner_id.lang.code}."),
+ 'user_signature': fields.boolean('Add Signature',
+ help="If checked, the user's signature will be appended to the text version "
+ "of the message"),
+ 'report_name': fields.char('Report Filename', size=200, translate=True,
+ help="Name to use for the generated report file (may contain placeholders)\n"
+ "The extension can be omitted and will then come from the report type."),
+ 'report_template':fields.many2one('ir.actions.report.xml', 'Optional report to print and attach'),
+ 'ref_ir_act_window':fields.many2one('ir.actions.act_window', 'Sidebar action', readonly=True,
+ help="Sidebar action to make this template available on records "
+ "of the related document model"),
+ 'ref_ir_value':fields.many2one('ir.values', 'Sidebar button', readonly=True,
+ help="Sidebar button to open the sidebar action"),
+ 'track_campaign_item': fields.boolean('Resource Tracking',
+ help="Enable this is you wish to include a special tracking marker "
+ "in outgoing emails so you can identify replies and link "
+ "them back to the corresponding resource record. "
+ "This is useful for CRM leads for example"),
+
+ # Overridden mail.message.common fields for technical reasons:
+ 'model': fields.related('model_id','model', type='char', string='Related Document model',
+ size=128, select=True, store=True, readonly=True),
+ # we need a separate m2m table to avoid ID collisions with the original mail.message entries
+ 'attachment_ids': fields.many2many('ir.attachment', 'email_template_attachment_rel', 'email_template_id',
+ 'attachment_id', 'Files to attach',
+ help="You may attach files to this template, to be added to all "
+ "emails created from this template"),
+
+ # Overridden mail.message.common fields to make tooltips more appropriate:
+ 'subject':fields.char('Subject', size=512, translate=True, help="Subject (placeholders may be used here)",),
+ 'email_from': fields.char('From', size=128, help="Sender address (placeholders may be used here)"),
+ 'email_to': fields.char('To', size=256, help="Comma-separated recipient addresses (placeholders may be used here)"),
+ 'email_cc': fields.char('Cc', size=256, help="Carbon copy recipients (placeholders may be used here)"),
+ 'email_bcc': fields.char('Bcc', size=256, help="Blind carbon copy recipients (placeholders may be used here)"),
+ 'reply_to': fields.char('Reply-To', size=250, help="Preferred response address (placeholders may be used here)"),
+ 'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing Mail Server', readonly=False,
+ help="Optional preferred server for outgoing mails. If not set, the highest "
+ "priority one will be used."),
+ 'body_text': fields.text('Text contents', translate=True, help="Plaintext version of the message (placeholders may be used here)"),
+ 'body_html': fields.text('Rich-text contents', help="Rich-text/HTML version of the message (placeholders may be used here)"),
+ 'message_id': fields.char('Message-Id', size=256, help="Message-ID SMTP header to use in outgoing messages based on this template. "
+ "Please note that this overrides the 'Resource Tracking' option, "
+ "so if you simply need to track replies to outgoing emails, enable "
+ "that option instead.\n"
+ "Placeholders must be used here, as this value always needs to be unique!"),
+
+ # Fake fields used to implement the placeholder assistant
+ 'model_object_field': fields.many2one('ir.model.fields', string="Field",
+ help="Select target field from the related document model.\n"
+ "If it is a relationship field you will be able to select "
+ "a target field at the destination of the relationship."),
+ 'sub_object': fields.many2one('ir.model', 'Sub-model', readonly=True,
+ help="When a relationship field is selected as first field, "
+ "this field shows the document model the relationship goes to."),
+ 'sub_model_object_field': fields.many2one('ir.model.fields', 'Sub-field',
+ help="When a relationship field is selected as first field, "
+ "this field lets you select the target field within the "
+ "destination document model (sub-model)."),
+ 'null_value': fields.char('Null value', help="Optional value to use if the target field is empty", size=128),
+ 'copyvalue': fields.char('Expression', size=256, help="Final placeholder expression, to be copy-pasted in the desired template field."),
}
_defaults = {
- 'template_language' : lambda *a:'mako',
-
+ 'track_campaign_item': True
}
- _sql_constraints = [
- ('name', 'unique (name)','The template name must be unique !')
- ]
-
def create_action(self, cr, uid, ids, context=None):
vals = {}
- if context is None:
- context = {}
- template_obj = self.browse(cr, uid, ids, context=context)[0]
- src_obj = template_obj.object_name.model
- vals['ref_ir_act_window'] = self.pool.get('ir.actions.act_window').create(cr, uid, {
- 'name': template_obj.name,
- 'type': 'ir.actions.act_window',
- 'res_model': 'email_template.send.wizard',
- 'src_model': src_obj,
- 'view_type': 'form',
- 'context': "{'src_model':'%s','template_id':'%d','src_rec_id':active_id,'src_rec_ids':active_ids}" % (src_obj, template_obj.id),
- 'view_mode':'form,tree',
- 'view_id': self.pool.get('ir.ui.view').search(cr, uid, [('name', '=', 'email_template.send.wizard.form')], context=context)[0],
- 'target': 'new',
- 'auto_refresh':1
- }, context)
- ir_values_obj = self.pool.get('ir.values')
- vals['ref_ir_value'] = ir_values_obj.create(cr, uid, {
- 'name': _('Send Mail (%s)') % template_obj.name,
- 'model': src_obj,
- 'key2': 'client_action_multi',
- 'value': "ir.actions.act_window," + str(vals['ref_ir_act_window']),
- 'object': True,
- }, context)
+ action_obj = self.pool.get('ir.actions.act_window')
+ data_obj = self.pool.get('ir.model.data')
+ for template in self.browse(cr, uid, ids, context=context):
+ src_obj = template.model_id.model
+ model_data_id = data_obj._get_id(cr, uid, 'mail', 'email_compose_message_wizard_form')
+ res_id = data_obj.browse(cr, uid, model_data_id, context=context).res_id
+ vals['ref_ir_act_window'] = action_obj.create(cr, uid, {
+ 'name': template.name,
+ 'type': 'ir.actions.act_window',
+ 'res_model': 'mail.compose.message',
+ 'src_model': src_obj,
+ 'view_type': 'form',
+ 'context': "{'mail.compose.message.mode':'mass_mail'}",
+ 'view_mode':'form,tree',
+ 'view_id': res_id,
+ 'target': 'new',
+ 'auto_refresh':1
+ }, context)
+ vals['ref_ir_value'] = self.pool.get('ir.values').create(cr, uid, {
+ 'name': _('Send Mail (%s)') % template.name,
+ 'model': src_obj,
+ 'key2': 'client_action_multi',
+ 'value': "ir.actions.act_window," + str(vals['ref_ir_act_window']),
+ 'object': True,
+ }, context)
self.write(cr, uid, ids, {
- 'ref_ir_act_window': vals['ref_ir_act_window'],
- 'ref_ir_value': vals['ref_ir_value'],
- }, context)
+ 'ref_ir_act_window': vals.get('ref_ir_act_window',False),
+ 'ref_ir_value': vals.get('ref_ir_value',False),
+ }, context)
return True
def unlink_action(self, cr, uid, ids, context=None):
@@ -304,9 +213,6 @@ This is useful for CRM leads for example"),
ir_values_obj.unlink(cr, uid, template.ref_ir_value.id, context)
except:
raise osv.except_osv(_("Warning"), _("Deletion of Record failed"))
-
- def delete_action(self, cr, uid, ids, context=None):
- self.unlink_action(cr, uid, ids, context=context)
return True
def unlink(self, cr, uid, ids, context=None):
@@ -314,511 +220,167 @@ This is useful for CRM leads for example"),
return super(email_template, self).unlink(cr, uid, ids, context=context)
def copy(self, cr, uid, id, default=None, context=None):
+ template = self.browse(cr, uid, id, context=context)
if default is None:
default = {}
default = default.copy()
- old = self.read(cr, uid, id, ['name'], context=context)
- new_name = _("Copy of template %s") % old.get('name', 'No Name')
- check = self.search(cr, uid, [('name', '=', new_name)], context=context)
- if check:
- new_name = new_name + '_' + random.choice('abcdefghij') + random.choice('lmnopqrs') + random.choice('tuvwzyz')
- default.update({'name':new_name})
+ default['name'] = template.name + _('(copy)')
return super(email_template, self).copy(cr, uid, id, default, context)
- def build_expression(self, field_name, sub_field_name, null_value, template_language='mako'):
- """
- Returns a template expression based on data provided
- @param field_name: field name
- @param sub_field_name: sub field name (M2O)
- @param null_value: default value if the target value is empty
- @param template_language: name of template engine
- @return: computed expression
- """
+ def build_expression(self, field_name, sub_field_name, null_value):
+ """Returns a placeholder expression for use in a template field,
+ based on the values provided in the placeholder assistant.
+ :param field_name: main field name
+ :param sub_field_name: sub field name (M2O)
+ :param null_value: default value if the target value is empty
+ :return: final placeholder expression
+ """
expression = ''
- if template_language == 'mako':
- if field_name:
- expression = "${object." + field_name
- if sub_field_name:
- expression += "." + sub_field_name
- if null_value:
- expression += " or '''%s'''" % null_value
- expression += "}"
- elif template_language == 'django':
- if field_name:
- expression = "{{object." + field_name
- if sub_field_name:
- expression += "." + sub_field_name
- if null_value:
- expression += "|default: '''%s'''" % null_value
- expression += "}}"
+ if field_name:
+ expression = "${object." + field_name
+ if sub_field_name:
+ expression += "." + sub_field_name
+ if null_value:
+ expression += " or '''%s'''" % null_value
+ expression += "}"
return expression
- def onchange_model_object_field(self, cr, uid, ids, model_object_field, template_language, context=None):
- if not model_object_field:
- return {}
- result = {}
- field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
- #Check if field is relational
- if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
- res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
- if res_ids:
- result['sub_object'] = res_ids[0]
- result['copyvalue'] = self.build_expression(False,
- False,
- False,
- template_language)
- result['sub_model_object_field'] = False
- result['null_value'] = False
- else:
- #Its a simple field... just compute placeholder
- result['sub_object'] = False
- result['copyvalue'] = self.build_expression(field_obj.name,
- False,
- False,
- template_language
- )
- result['sub_model_object_field'] = False
- result['null_value'] = False
+ def onchange_sub_model_object_value_field(self, cr, uid, ids, model_object_field, sub_model_object_field=False, null_value=None, context=None):
+ result = {
+ 'sub_object': False,
+ 'copyvalue': False,
+ 'sub_model_object_field': False,
+ 'null_value': False
+ }
+ if model_object_field:
+ fields_obj = self.pool.get('ir.model.fields')
+ field_value = fields_obj.browse(cr, uid, model_object_field, context)
+ if field_value.ttype in ['many2one', 'one2many', 'many2many']:
+ res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_value.relation)], context=context)
+ sub_field_value = False
+ if sub_model_object_field:
+ sub_field_value = fields_obj.browse(cr, uid, sub_model_object_field, context)
+ if res_ids:
+ result.update({
+ 'sub_object': res_ids[0],
+ 'copyvalue': self.build_expression(field_value.name, sub_field_value and sub_field_value.name or False, null_value or False),
+ 'sub_model_object_field': sub_model_object_field or False,
+ 'null_value': null_value or False
+ })
+ else:
+ result.update({
+ 'copyvalue': self.build_expression(field_value.name, False, null_value or False),
+ 'null_value': null_value or False
+ })
return {'value':result}
- def onchange_sub_model_object_field(self, cr, uid, ids, model_object_field, sub_model_object_field, template_language, context=None):
- if not model_object_field or not sub_model_object_field:
- return {}
- result = {}
- field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
- if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
- res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
- sub_field_obj = self.pool.get('ir.model.fields').browse(cr, uid, sub_model_object_field, context)
- if res_ids:
- result['sub_object'] = res_ids[0]
- result['copyvalue'] = self.build_expression(field_obj.name,
- sub_field_obj.name,
- False,
- template_language
- )
- result['sub_model_object_field'] = sub_model_object_field
- result['null_value'] = False
- else:
- #Its a simple field... just compute placeholder
- result['sub_object'] = False
- result['copyvalue'] = self.build_expression(field_obj.name,
- False,
- False,
- template_language
- )
- result['sub_model_object_field'] = False
- result['null_value'] = False
- return {'value':result}
- def onchange_null_value(self, cr, uid, ids, model_object_field, sub_model_object_field, null_value, template_language, context=None):
- if not model_object_field and not null_value:
- return {}
- result = {}
- field_obj = self.pool.get('ir.model.fields').browse(cr, uid, model_object_field, context)
- if field_obj.ttype in ['many2one', 'one2many', 'many2many']:
- res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_obj.relation)], context=context)
- sub_field_obj = self.pool.get('ir.model.fields').browse(cr, uid, sub_model_object_field, context)
- if res_ids:
- result['sub_object'] = res_ids[0]
- result['copyvalue'] = self.build_expression(field_obj.name,
- sub_field_obj.name,
- null_value,
- template_language
- )
- result['sub_model_object_field'] = sub_model_object_field
- result['null_value'] = null_value
- else:
- #Its a simple field... just compute placeholder
- result['sub_object'] = False
- result['copyvalue'] = self.build_expression(field_obj.name,
- False,
- null_value,
- template_language
- )
- result['sub_model_object_field'] = False
- result['null_value'] = null_value
- return {'value':result}
+ def generate_email(self, cr, uid, template_id, res_id, context=None):
+ """Generates an email from the template for given (model, res_id) pair.
- def _add_attachment(self, cursor, user, mailbox_id, name, data, filename, context=None):
- """
- Add an attachment to a given mailbox entry.
-
- :param data: base64 encoded attachment data to store
- """
- attachment_obj = self.pool.get('ir.attachment')
- attachment_data = {
- 'name': (name or '') + _(' (Email Attachment)'),
- 'datas': data,
- 'datas_fname': filename,
- 'description': name or _('No Description'),
- 'res_model':'email_template.mailbox',
- 'res_id': mailbox_id,
- }
- attachment_id = attachment_obj.create(cursor,
- user,
- attachment_data,
- context)
- if attachment_id:
- self.pool.get('email_template.mailbox').write(
- cursor,
- user,
- mailbox_id,
- {
- 'attachments_ids':[(4, attachment_id)],
- 'mail_type':'multipart/mixed'
- },
- context)
-
- def generate_attach_reports(self,
- cursor,
- user,
- template,
- record_id,
- mail,
- context=None):
- """
- Generate report to be attached and attach it
- to the email, and add any directly attached files as well.
-
- @param cursor: Database Cursor
- @param user: ID of User
- @param template: Browse record of
- template
- @param record_id: ID of the target model
- for which this mail has
- to be generated
- @param mail: Browse record of email object
- @return: True
- """
- if template.report_template:
- reportname = 'report.' + \
- self.pool.get('ir.actions.report.xml').read(
- cursor,
- user,
- template.report_template.id,
- ['report_name'],
- context)['report_name']
- service = netsvc.LocalService(reportname)
- data = {}
- data['model'] = template.model_int_name
- (result, format) = service.create(cursor,
- user,
- [record_id],
- data,
- context)
- fname = tools.ustr(get_value(cursor, user, record_id,
- template.file_name, template, context)
- or 'Report')
- ext = '.' + format
- if not fname.endswith(ext):
- fname += ext
- self._add_attachment(cursor, user, mail.id, mail.subject, base64.b64encode(result), fname, context)
-
- if template.attachment_ids:
- for attachment in template.attachment_ids:
- self._add_attachment(cursor, user, mail.id, attachment.name, attachment.datas, attachment.datas_fname, context)
-
- return True
-
- def _generate_mailbox_item_from_template(self,
- cursor,
- user,
- template,
- record_id,
- context=None):
- """
- Generates an email from the template for
- record record_id of target object
-
- @param cursor: Database Cursor
- @param user: ID of User
- @param template: Browse record of
- template
- @param record_id: ID of the target model
- for which this mail has
- to be generated
- @return: ID of created object
+ :param template_id: id of the template to render.
+ :param res_id: id of the record to use for rendering the template (model
+ is taken from template definition)
+ :returns: a dict containing all relevant fields for creating a new
+ mail.message entry, with the addition one additional
+ special key ``attachments`` containing a list of
"""
if context is None:
context = {}
- #If account to send from is in context select it, else use enforced account
- if 'account_id' in context.keys():
- from_account = self.pool.get('email_template.account').read(
- cursor,
- user,
- context.get('account_id'),
- ['name', 'email_id'],
- context
- )
- else:
- from_account = {
- 'id':template.from_account.id,
- 'name':template.from_account.name,
- 'email_id':template.from_account.email_id
- }
- lang = get_value(cursor,
- user,
- record_id,
- template.lang,
- template,
- context)
- if lang:
- ctx = context.copy()
- ctx.update({'lang':lang})
- template = self.browse(cursor, user, template.id, context=ctx)
-
- # determine name of sender, either it is specified in email_id or we
- # use the account name
- email_id = from_account['email_id'].strip()
- email_from = re.findall(r'([^ ,<@]+@[^> ,]+)', email_id)[0]
- if email_from != email_id:
- # we should keep it all, name is probably specified in the address
- email_from = from_account['email_id']
- else:
- email_from = tools.ustr(from_account['name']) + "<" + tools.ustr(email_id) + ">"
-
- # FIXME: should do this in a loop and rename template fields to the corresponding
- # mailbox fields. (makes no sense to have different names I think.
- mailbox_values = {
- 'email_from': email_from,
- 'email_to':get_value(cursor,
- user,
- record_id,
- template.def_to,
- template,
- context),
- 'email_cc':get_value(cursor,
- user,
- record_id,
- template.def_cc,
- template,
- context),
- 'email_bcc':get_value(cursor,
- user,
- record_id,
- template.def_bcc,
- template,
- context),
- 'reply_to':get_value(cursor,
- user,
- record_id,
- template.reply_to,
- template,
- context),
- 'subject':get_value(cursor,
- user,
- record_id,
- template.def_subject,
- template,
- context),
- 'body_text':get_value(cursor,
- user,
- record_id,
- template.def_body_text,
- template,
- context),
- 'body_html':get_value(cursor,
- user,
- record_id,
- template.def_body_html,
- template,
- context),
- 'account_id' :from_account['id'],
- #This is a mandatory field when automatic emails are sent
- 'state':'na',
- 'folder':'drafts',
- 'mail_type':'multipart/alternative',
+ values = {
+ 'subject': False,
+ 'body_text': False,
+ 'body_html': False,
+ 'email_from': False,
+ 'email_to': False,
+ 'email_cc': False,
+ 'email_bcc': False,
+ 'reply_to': False,
+ 'auto_delete': False,
+ 'model': False,
+ 'res_id': False,
+ 'mail_server_id': False,
+ 'attachments': False,
+ 'attachment_ids': False,
+ 'message_id': False,
+ 'state': 'outgoing',
}
-
- if template['message_id']:
- # use provided message_id with placeholders
- mailbox_values.update({'message_id': get_value(cursor, user, record_id, template['message_id'], template, context)})
-
- elif template['track_campaign_item']:
- # get appropriate message-id
- mailbox_values.update({'message_id': tools.misc.generate_tracking_message_id(record_id)})
-
- if not mailbox_values['account_id']:
- raise Exception("Unable to send the mail. No account linked to the template.")
- #Use signatures if allowed
- if template.use_sign:
- sign = self.pool.get('res.users').read(cursor,
- user,
- user,
- ['signature'],
- context)['signature']
- if mailbox_values['body_text']:
- mailbox_values['body_text'] += sign
- if mailbox_values['body_html']:
- mailbox_values['body_html'] += sign
- mailbox_id = self.pool.get('email_template.mailbox').create(
- cursor,
- user,
- mailbox_values,
- context)
-
- return mailbox_id
-
-
- def generate_mail(self,
- cursor,
- user,
- template_id,
- record_ids,
- context=None):
- if context is None:
- context = {}
- template = self.browse(cursor, user, template_id, context=context)
- if not template:
- raise Exception("The requested template could not be loaded")
- result = True
- mailbox_obj = self.pool.get('email_template.mailbox')
- for record_id in record_ids:
- mailbox_id = self._generate_mailbox_item_from_template(
- cursor,
- user,
- template,
- record_id,
- context)
- mail = mailbox_obj.browse(
- cursor,
- user,
- mailbox_id,
- context=context
- )
- if template.report_template or template.attachment_ids:
- self.generate_attach_reports(
- cursor,
- user,
- template,
- record_id,
- mail,
- context
- )
-
- self.pool.get('email_template.mailbox').write(
- cursor,
- user,
- mailbox_id,
- {'folder':'outbox'},
- context=context
- )
- # TODO : manage return value of all the records
- result = self.pool.get('email_template.mailbox').send_this_mail(cursor, user, [mailbox_id], context)
- return result
-
-email_template()
-
-
-## FIXME: this class duplicates a lot of features of the email template send wizard,
-## one of the 2 should inherit from the other!
-
-class email_template_preview(osv.osv_memory):
- _name = "email_template.preview"
- _description = "Email Template Preview"
-
- def _get_model_recs(self, cr, uid, context=None):
- if context is None:
- context = {}
- #Fills up the selection box which allows records from the selected object to be displayed
- self.context = context
- if 'template_id' in context:
- ref_obj_id = self.pool.get('email.template').read(cr, uid, context['template_id'], ['object_name'], context)
- ref_obj_name = self.pool.get('ir.model').read(cr, uid, ref_obj_id['object_name'][0], ['model'], context)['model']
- model_obj = self.pool.get(ref_obj_name)
- ref_obj_ids = model_obj.search(cr, uid, [], 0, 20, 'id', context=context)
- if not ref_obj_ids:
- ref_obj_ids = []
-
- # also add the default one if requested, otherwise it won't be available for selection:
- default_id = context.get('default_rel_model_ref')
- if default_id and default_id not in ref_obj_ids:
- ref_obj_ids.insert(0, default_id)
- return model_obj.name_get(cr, uid, ref_obj_ids, context)
- return []
-
- def default_get(self, cr, uid, fields, context=None):
- if context is None:
- context = {}
- result = super(email_template_preview, self).default_get(cr, uid, fields, context=context)
- if (not fields or 'rel_model_ref' in fields) and 'template_id' in context \
- and not result.get('rel_model_ref'):
- selectables = self._get_model_recs(cr, uid, context=context)
- result['rel_model_ref'] = selectables and selectables[0][0] or False
- return result
-
- def _default_model(self, cursor, user, context=None):
- """
- Returns the default value for model field
- @param cursor: Database Cursor
- @param user: ID of current user
- @param context: OpenERP Context
- """
- return self.pool.get('email.template').read(
- cursor,
- user,
- context['template_id'],
- ['object_name'],
- context).get('object_name', False)
-
- _columns = {
- 'ref_template':fields.many2one(
- 'email.template',
- 'Template', readonly=True),
- 'rel_model':fields.many2one('ir.model', 'Model', readonly=True),
- 'rel_model_ref':fields.selection(_get_model_recs, 'Referred Document'),
- 'to':fields.char('To', size=250, readonly=True),
- 'cc':fields.char('CC', size=250, readonly=True),
- 'bcc':fields.char('BCC', size=250, readonly=True),
- 'reply_to':fields.char('Reply-To',
- size=250,
- help="The address recipients should reply to,"
- " if different from the From address."
- " Placeholders can be used here."),
- 'message_id':fields.char('Message-ID',
- size=250,
- help="The Message-ID header value, if you need to"
- "specify it, for example to automatically recognize the replies later."
- " Placeholders can be used here."),
- 'subject':fields.char('Subject', size=200, readonly=True),
- 'body_text':fields.text('Body', readonly=True),
- 'body_html':fields.text('Body', readonly=True),
- 'report':fields.char('Report Name', size=100, readonly=True),
- }
- _defaults = {
- 'ref_template': lambda self, cr, uid, ctx:ctx['template_id'] or False,
- 'rel_model': _default_model,
- }
- def on_change_ref(self, cr, uid, ids, rel_model_ref, context=None):
- if context is None:
- context = {}
- if not rel_model_ref:
- return {}
- vals = {}
- if context == {}:
- context = self.context
- template = self.pool.get('email.template').browse(cr, uid, context['template_id'], context)
- #Search translated template
- lang = get_value(cr, uid, rel_model_ref, template.lang, template, context)
- if lang:
+ if not template_id:
+ return values
+
+ report_xml_pool = self.pool.get('ir.actions.report.xml')
+ template = self.get_email_template(cr, uid, template_id, res_id, context)
+
+ for field in ['subject', 'body_text', 'body_html', 'email_from',
+ 'email_to', 'email_cc', 'email_bcc', 'reply_to',
+ 'message_id']:
+ values[field] = self.render_template(cr, uid, getattr(template, field),
+ template.model, res_id, context=context) \
+ or False
+
+ if template.user_signature:
+ signature = self.pool.get('res.users').browse(cr, uid, uid, context).signature
+ values['body_text'] += '\n\n' + signature
+
+ values.update(mail_server_id = template.mail_server_id.id or False,
+ auto_delete = template.auto_delete,
+ model=template.model,
+ res_id=res_id or False)
+
+ attachments = {}
+ # Add report as a Document
+ if template.report_template:
+ report_name = template.report_name
+ report_service = 'report.' + report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name
+ # Ensure report is rendered using template's language
ctx = context.copy()
- ctx.update({'lang':lang})
- template = self.pool.get('email.template').browse(cr, uid, context['template_id'], ctx)
- vals['to'] = get_value(cr, uid, rel_model_ref, template.def_to, template, context)
- vals['cc'] = get_value(cr, uid, rel_model_ref, template.def_cc, template, context)
- vals['bcc'] = get_value(cr, uid, rel_model_ref, template.def_bcc, template, context)
- vals['reply_to'] = get_value(cr, uid, rel_model_ref, template.reply_to, template, context)
- if template.message_id:
- vals['message_id'] = get_value(cr, uid, rel_model_ref, template.message_id, template, context)
- elif template.track_campaign_item:
- vals['message_id'] = tools.misc.generate_tracking_message_id(rel_model_ref)
- vals['subject'] = get_value(cr, uid, rel_model_ref, template.def_subject, template, context)
- vals['body_text'] = get_value(cr, uid, rel_model_ref, template.def_body_text, template, context)
- vals['body_html'] = get_value(cr, uid, rel_model_ref, template.def_body_html, template, context)
- vals['report'] = get_value(cr, uid, rel_model_ref, template.file_name, template, context)
- return {'value':vals}
-
-email_template_preview()
+ if template.lang:
+ ctx['lang'] = self.render_template(cr, uid, template.lang, template.model, res_id, context)
+ service = netsvc.LocalService(report_service)
+ (result, format) = service.create(cr, uid, [res_id], {'model': template.model}, ctx)
+ result = base64.b64encode(result)
+ if not report_name:
+ report_name = report_service
+ ext = "." + format
+ if not report_name.endswith(ext):
+ report_name += ext
+ attachments[report_name] = result
+
+ # Add document attachments
+ for attach in template.attachment_ids:
+ # keep the bytes as fetched from the db, base64 encoded
+ attachments[attach.datas_fname] = attach.datas
+
+ values['attachments'] = attachments
+ return values
+
+ def send_mail(self, cr, uid, template_id, res_id, context=None):
+ """Generates a new mail message for the given template and record,
+ and schedule it for delivery through the ``mail`` module's scheduler.
+
+ :param int template_id: id of the template to render
+ :param int res_id: id of the record to render the template with
+ (model is taken from the template)
+ """
+ mail_message = self.pool.get('mail.message')
+ ir_attachment = self.pool.get('ir.attachment')
+ template = self.browse(cr, uid, template_id, context)
+ values = self.generate_email(cr, uid, template_id, res_id, context=context)
+ attachments = values.pop('attachments') or {}
+ message_id = mail_message.create(cr, uid, values, context=context)
+ # link attachments
+ attachment_ids = []
+ for fname, fcontent in attachments.iteritems():
+ attachment_data = {
+ 'name': fname,
+ 'datas_fname': fname,
+ 'datas': fcontent,
+ 'res_model': mail_message._name,
+ 'res_id': message_id,
+ }
+ if context.has_key('default_type'):
+ del context['default_type']
+ attachment_ids.append(ir_attachment.create(cr, uid, attachment_data, context))
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diff --git a/addons/email_template/email_template_account.py b/addons/email_template/email_template_account.py
deleted file mode 100644
index a5f51400c8a..00000000000
--- a/addons/email_template/email_template_account.py
+++ /dev/null
@@ -1,470 +0,0 @@
-# -*- coding: utf-8 -*-
-##############################################################################
-#
-# OpenERP, Open Source Management Solution
-# Copyright (C) 2009 Sharoon Thomas
-# Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>
-#
-##############################################################################
-
-from osv import osv, fields
-import re
-import smtplib
-import base64
-from email import Encoders
-from email.mime.base import MIMEBase
-from email.mime.multipart import MIMEMultipart
-from email.mime.text import MIMEText
-from email.header import decode_header, Header
-from email.utils import formatdate
-import netsvc
-import datetime
-from tools.translate import _
-import tools
-import logging
-
-EMAIL_PATTERN = re.compile(r'([^()\[\] ,<:\\>@";]+@[^()\[\] ,<:\\>@";]+)') # See RFC822
-def extract_emails(emails_str):
- """
- Returns a list of email addresses recognized in a string, ignoring the rest of the string.
- extract_emails('a@b.com,c@bcom, "John Doe" <d@b.com> , e@b.com') -> ['a@b.com','c@bcom', 'd@b.com', 'e@b.com']"
- """
- return EMAIL_PATTERN.findall(emails_str)
-
-
-def extract_emails_from_dict(addresses={}):
- """
- Extracts email addresses from a dictionary with comma-separated address string values, handling
- separately the To, CC, BCC and Reply-To addresses.
-
- :param addresses: a dictionary of addresses in the form {'To': 'a@b.com,c@bcom; d@b.com;e@b.com' , 'CC': 'e@b.com;f@b.com', ... }
- :return: a dictionary with a list of separate addresses for each header (To, CC, BCC), with an additional key 'all-recipients'
- containing all addresses for the 'To', 'CC', 'BCC' entries.
- """
- result = {'all-recipients':[]}
- keys = ['To', 'CC', 'BCC', 'Reply-To']
- for each in keys:
- emails = extract_emails(addresses.get(each, u''))
- while u'' in emails:
- emails.remove(u'')
- result[each] = emails
- if each != 'Reply-To':
- result['all-recipients'].extend(emails)
- return result
-
-class email_template_account(osv.osv):
- """
- Object to store email account settings
- """
- _name = "email_template.account"
- _known_content_types = ['multipart/mixed',
- 'multipart/alternative',
- 'multipart/related',
- 'text/plain',
- 'text/html'
- ]
- _columns = {
- 'name': fields.char('Description',
- size=64, required=True,
- readonly=True, select=True,
- help="The description is used as the Sender name along with the provided From Email, \
-unless it is already specified in the From Email, e.g: John Doe <john@doe.com>",
- states={'draft':[('readonly', False)]}),
- 'auto_delete': fields.boolean('Auto Delete', size=64, readonly=True,
- help="Permanently delete emails after sending",
- states={'draft':[('readonly', False)]}),
- 'user':fields.many2one('res.users',
- 'Related User', required=True,
- readonly=True, states={'draft':[('readonly', False)]}),
- 'email_id': fields.char('From Email',
- size=120, required=True,
- readonly=True, states={'draft':[('readonly', False)]} ,
- help="eg: 'john@doe.com' or 'John Doe <john@doe.com>'"),
- 'smtpserver': fields.char('Server',
- size=120, required=True,
- readonly=True, states={'draft':[('readonly', False)]},
- help="Enter name of outgoing server, eg: smtp.yourdomain.com"),
- 'smtpport': fields.integer('SMTP Port',
- size=64, required=True,
- readonly=True, states={'draft':[('readonly', False)]},
- help="Enter port number, eg: 25 or 587"),
- 'smtpuname': fields.char('User Name',
- size=120, required=False,
- readonly=True, states={'draft':[('readonly', False)]},
- help="Specify the username if your SMTP server requires authentication, "
- "otherwise leave it empty."),
- 'smtppass': fields.char('Password',
- size=120, invisible=True,
- required=False, readonly=True,
- states={'draft':[('readonly', False)]}),
- 'smtptls':fields.boolean('TLS',
- states={'draft':[('readonly', False)]}, readonly=True),
-
- 'smtpssl':fields.boolean('SSL/TLS (only in python 2.6)',
- states={'draft':[('readonly', False)]}, readonly=True),
- 'send_pref':fields.selection([
- ('html', 'HTML, otherwise Text'),
- ('text', 'Text, otherwise HTML'),
- ('alternative', 'Both HTML & Text (Alternative)'),
- ('mixed', 'Both HTML & Text (Mixed)')
- ], 'Mail Format', required=True),
- 'company':fields.selection([
- ('yes', 'Yes'),
- ('no', 'No')
- ], 'Corporate',
- readonly=True,
- help="Select if this mail account does not belong " \
- "to specific user but to the organization as a whole. " \
- "eg: info@companydomain.com",
- required=True, states={
- 'draft':[('readonly', False)]
- }),
-
- 'state':fields.selection([
- ('draft', 'Initiated'),
- ('suspended', 'Suspended'),
- ('approved', 'Approved')
- ],
- 'State', required=True, readonly=True),
- }
-
- _defaults = {
- 'name':lambda self, cursor, user, context:self.pool.get(
- 'res.users'
- ).read(
- cursor,
- user,
- user,
- ['name'],
- context
- )['name'],
- 'state':lambda * a:'draft',
- 'smtpport':lambda *a:25,
- 'smtpserver':lambda *a:'localhost',
- 'company':lambda *a:'yes',
- 'user':lambda self, cursor, user, context:user,
- 'send_pref':lambda *a: 'html',
- 'smtptls':lambda *a:True,
- }
-
- _sql_constraints = [
- (
- 'email_uniq',
- 'unique (email_id)',
- 'Another setting already exists with this email ID !')
- ]
-
- def name_get(self, cr, uid, ids, context=None):
- return [(a["id"], "%s (%s)" % (a['email_id'], a['name'])) for a in self.read(cr, uid, ids, ['name', 'email_id'], context=context)]
-
- def _constraint_unique(self, cursor, user, ids, context=None):
- """
- This makes sure that you dont give personal
- users two accounts with same ID (Validated in sql constaints)
- However this constraint exempts company accounts.
- Any no of co accounts for a user is allowed
- """
- if self.read(cursor, user, ids, ['company'])[0]['company'] == 'no':
- accounts = self.search(cursor, user, [
- ('user', '=', user),
- ('company', '=', 'no')
- ])
- if len(accounts) > 1 :
- return False
- else :
- return True
- else:
- return True
-
- _constraints = [
- (_constraint_unique,
- 'Error: You are not allowed to have more than 1 account.',
- [])
- ]
-
- def get_outgoing_server(self, cursor, user, ids, context=None):
- """
- Returns the Out Going Connection (SMTP) object
-
- @attention: DO NOT USE except_osv IN THIS METHOD
- @param cursor: Database Cursor
- @param user: ID of current user
- @param ids: ID/list of ids of current object for
- which connection is required
- First ID will be chosen from lists
- @param context: Context
-
- @return: SMTP server object or Exception
- """
- #Type cast ids to integer
- if type(ids) == list:
- ids = ids[0]
- this_object = self.browse(cursor, user, ids, context=context)
- if this_object:
- if this_object.smtpserver and this_object.smtpport:
- try:
- if this_object.smtpssl:
- serv = smtplib.SMTP_SSL(this_object.smtpserver, this_object.smtpport)
- else:
- serv = smtplib.SMTP(this_object.smtpserver, this_object.smtpport)
- if this_object.smtptls:
- serv.ehlo()
- serv.starttls()
- serv.ehlo()
- except Exception, error:
- raise error
- try:
- if serv.has_extn('AUTH') or this_object.smtpuname or this_object.smtppass:
- serv.login(str(this_object.smtpuname), str(this_object.smtppass))
- except Exception, error:
- raise error
- return serv
- raise Exception(_("SMTP SERVER or PORT not specified"))
- raise Exception(_("Core connection for the given ID does not exist"))
-
- def check_outgoing_connection(self, cursor, user, ids, context=None):
- """
- checks SMTP credentials and confirms if outgoing connection works
- (Attached to button)
- @param cursor: Database Cursor
- @param user: ID of current user
- @param ids: list of ids of current object for
- which connection is required
- @param context: Context
- """
- try:
- self.get_outgoing_server(cursor, user, ids, context)
- raise osv.except_osv(_("SMTP Test Connection Was Successful"), '')
- except osv.except_osv, success_message:
- raise success_message
- except Exception, error:
- raise osv.except_osv(
- _("Out going connection test failed"),
- _("Reason: %s") % tools.ustr(error)
- )
-
- def do_approval(self, cr, uid, ids, context=None):
- #TODO: Check if user has rights
- self.write(cr, uid, ids, {'state':'approved'}, context=context)
-# wf_service = netsvc.LocalService("workflow")
-
- def smtp_connection(self, cursor, user, id, context=None):
- """
- This method should now wrap smtp_connection
- """
- #This function returns a SMTP server object
- logger = netsvc.Logger()
- core_obj = self.browse(cursor, user, id, context=context)
- if core_obj.smtpserver and core_obj.smtpport and core_obj.state == 'approved':
- try:
- serv = self.get_outgoing_server(cursor, user, id, context)
- except Exception, error:
- logger.notifyChannel(_("Email Template"), netsvc.LOG_ERROR, _("Mail from Account %s failed on login. Probable Reason:Could not login to server\nError: %s") % (id, tools.ustr(error)))
- return False
- #Everything is complete, now return the connection
- return serv
- else:
- logger.notifyChannel(_("Email Template"), netsvc.LOG_ERROR, _("Mail from Account %s failed. Probable Reason:Account not approved") % id)
- return False
-
-#**************************** MAIL SENDING FEATURES ***********************#
-
-
-
-
- def send_mail(self, cr, uid, ids, addresses, subject='', body=None, payload=None, message_id=None, context=None):
- #TODO: Replace all this with a single email object
- if body is None:
- body = {}
- if payload is None:
- payload = {}
- if context is None:
- context = {}
- logger = netsvc.Logger()
- for id in ids:
- core_obj = self.browse(cr, uid, id, context)
- serv = self.smtp_connection(cr, uid, id)
- if serv:
- try:
- # Prepare multipart containers depending on data
- text_subtype = (core_obj.send_pref == 'alternative') and 'alternative' or 'mixed'
- # Need a multipart/mixed wrapper for attachments if content is alternative
- if payload and text_subtype == 'alternative':
- payload_part = MIMEMultipart(_subtype='mixed')
- text_part = MIMEMultipart(_subtype=text_subtype)
- payload_part.attach(text_part)
- else:
- # otherwise a single multipart/mixed will do the whole job
- payload_part = text_part = MIMEMultipart(_subtype=text_subtype)
-
- if subject:
- payload_part['Subject'] = subject
- from_email = core_obj.email_id
- if '<' in from_email:
- # We have a structured email address, keep it untouched
- payload_part['From'] = Header(core_obj.email_id, 'utf-8').encode()
- else:
- # Plain email address, construct a structured one based on the name:
- sender_name = Header(core_obj.name, 'utf-8').encode()
- payload_part['From'] = sender_name + " <" + core_obj.email_id + ">"
- payload_part['Organization'] = tools.ustr(core_obj.user.company_id.name)
- payload_part['Date'] = formatdate()
- addresses_l = extract_emails_from_dict(addresses)
- if addresses_l['To']:
- payload_part['To'] = u','.join(addresses_l['To'])
- if addresses_l['CC']:
- payload_part['CC'] = u','.join(addresses_l['CC'])
- if addresses_l['Reply-To']:
- payload_part['Reply-To'] = addresses_l['Reply-To'][0]
- if message_id:
- payload_part['Message-ID'] = message_id
- if body.get('text', False):
- temp_body_text = body.get('text', '')
- l = len(temp_body_text.replace(' ', '').replace('\r', '').replace('\n', ''))
- if l == 0:
- body['text'] = u'No Mail Message'
- # Attach parts into message container.
- # According to RFC 2046, the last part of a multipart message, in this case
- # the HTML message, is best and preferred.
- if core_obj.send_pref in ('text', 'mixed', 'alternative'):
- body_text = body.get('text', u'<Empty Message>')
- body_text = tools.ustr(body_text)
- text_part.attach(MIMEText(body_text.encode("utf-8"), _charset='UTF-8'))
- if core_obj.send_pref in ('html', 'mixed', 'alternative'):
- html_body = body.get('html', u'')
- if len(html_body) == 0 or html_body == u'':
- html_body = body.get('text', u'<p>&lt;Empty Message&gt;</p>').replace('\n', '<br/>').replace('\r', '<br/>')
- html_body = tools.ustr(html_body)
- text_part.attach(MIMEText(html_body.encode("utf-8"), _subtype='html', _charset='UTF-8'))
-
- #Now add attachments if any, wrapping into a container multipart/mixed if needed
- if payload:
- for file in payload:
- part = MIMEBase('application', "octet-stream")
- part.set_payload(base64.decodestring(payload[file]))
- part.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
- Encoders.encode_base64(part)
- payload_part.attach(part)
- except Exception, error:
- logger.notifyChannel(_("Email Template"), netsvc.LOG_ERROR, _("Mail from Account %s failed. Probable Reason:MIME Error\nDescription: %s") % (id, tools.ustr(error)))
- return {'error_msg': _("Server Send Error\nDescription: %s")%error}
- try:
- serv.sendmail(payload_part['From'], addresses_l['all-recipients'], payload_part.as_string())
- except Exception, error:
- logging.getLogger('email_template').error(_("Mail from Account %s failed. Probable Reason: Server Send Error\n Description: %s"), id, tools.ustr(error), exc_info=True)
- return {'error_msg': _("Server Send Error\nDescription: %s") % tools.ustr(error)}
- #The mail sending is complete
- serv.close()
- logger.notifyChannel(_("Email Template"), netsvc.LOG_INFO, _("Mail from Account %s successfully Sent.") % (id))
- return True
- else:
- logger.notifyChannel(_("Email Template"), netsvc.LOG_ERROR, _("Mail from Account %s failed. Probable Reason:Account not approved") % id)
- return {'nodestroy':True,'error_msg': _("Mail from Account %s failed. Probable Reason:Account not approved")% id}
-
- def extracttime(self, time_as_string):
- """
- TODO: DOC THis
- """
- logger = netsvc.Logger()
- #The standard email dates are of format similar to:
- #Thu, 8 Oct 2009 09:35:42 +0200
- date_as_date = False
- convertor = {'+':1, '-':-1}
- try:
- time_as_string = time_as_string.replace(',', '')
- date_list = time_as_string.split(' ')
- date_temp_str = ' '.join(date_list[1:5])
- if len(date_list) >= 6:
- sign = convertor.get(date_list[5][0], False)
- else:
- sign = False
- try:
- dt = datetime.datetime.strptime(
- date_temp_str,
- "%d %b %Y %H:%M:%S")
- except:
- try:
- dt = datetime.datetime.strptime(
- date_temp_str,
- "%d %b %Y %H:%M")
- except:
- return False
- if sign:
- try:
- offset = datetime.timedelta(
- hours=sign * int(
- date_list[5][1:3]
- ),
- minutes=sign * int(
- date_list[5][3:5]
- )
- )
- except Exception, e2:
- """Looks like UT or GMT, just forget decoding"""
- return False
- else:
- offset = datetime.timedelta(hours=0)
- dt = dt + offset
- date_as_date = dt.strftime('%Y-%m-%d %H:%M:%S')
- except Exception, e:
- logger.notifyChannel(
- _("Email Template"),
- netsvc.LOG_WARNING,
- _(
- "Datetime Extraction failed.Date:%s \
- \tError:%s") % (
- time_as_string,
- tools.ustr(e))
- )
- return date_as_date
-
- def send_receive(self, cr, uid, ids, context=None):
- for id in ids:
- ctx = context.copy()
- ctx['filters'] = [('account_id', '=', id)]
- self.pool.get('email_template.mailbox').send_all_mail(cr, uid, [], context=ctx)
- return True
-
- def decode_header_text(self, text):
- """ Decode internationalized headers RFC2822.
- To, CC, BCC, Subject fields can contain
- text slices with different encodes, like:
- =?iso-8859-1?Q?Enric_Mart=ED?= <enricmarti@company.com>,
- =?Windows-1252?Q?David_G=F3mez?= <david@company.com>
- Sometimes they include extra " character at the beginning/
- end of the contact name, like:
- "=?iso-8859-1?Q?Enric_Mart=ED?=" <enricmarti@company.com>
- and decode_header() does not work well, so we use regular
- expressions (?= ? ? ?=) to split the text slices
- """
- if not text:
- return text
- p = re.compile("(=\?.*?\?.\?.*?\?=)")
- text2 = ''
- try:
- for t2 in p.split(text):
- text2 += ''.join(
- [s.decode(
- t or 'ascii'
- ) for (s, t) in decode_header(t2)]
- ).encode('utf-8')
- except:
- return text
- return text2
-
-email_template_account()
-
-# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diff --git a/addons/email_template/email_template_account_view.xml b/addons/email_template/email_template_account_view.xml
deleted file mode 100644
index 09f9062d187..00000000000
--- a/addons/email_template/email_template_account_view.xml
+++ /dev/null
@@ -1,124 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<openerp>
- <data>
-
- <menuitem name="Marketing" icon="terp-crm" id="base.marketing_menu" sequence="17"
- groups="marketing.group_marketing_user,marketing.group_marketing_manager"/>
- <menuitem name="Emails" id="base.menu_emails" parent="base.marketing_menu" sequence="5"/>
- <menuitem name="Email Template" id="menu_email_template" parent="base.menu_emails"/>
-
- <record model="ir.ui.view" id="email_template_account_form">
- <field name="name">email_template.account.form</field>
- <field name="model">email_template.account</field>
- <field name="type">form</field>
- <field name="arch" type="xml">
- <form string="Email Account Configuration">
- <group colspan="2">
- <field name="name" select="1" />
- </group>
- <notebook colspan="4">
- <page string="Outgoing">
- <separator string="Server Information" colspan="4" />
- <group colspan="4" col="4">
- <field name="smtpserver" select="1"/>
- <button name="check_outgoing_connection" type="object" string="Test Outgoing Connection" icon="gtk-network" colspan="2"/>
- <field name="smtpport" select="2" />
- <field name="smtpssl" select="2" />
- <field name="smtptls" select="2" />
- <field name="auto_delete" />
- </group>
- <separator string="User Information" colspan="4" />
- <group col="2" colspan="2">
- <field name="email_id" select="1" colspan="2" />
- <field name="smtppass" password="True" colspan="2" />
- <field name="company" select="2" colspan="2" />
- </group>
- <group col="2" colspan="2">
- <field name="smtpuname" select="1" colspan="2" />
- <field name="user" select="2" colspan="2" />
- <field name="send_pref" colspan="2" />
- </group>
- </page>
- </notebook>
- <group colspan="4" col="10">
- <field name="state" select="1"/>
- <button string="Approve Account" name="button_approval" states="draft" type="workflow" icon="terp-camera_test"/>
- <button string="Suspend Account" name="button_suspended" states="approved" type="workflow" icon="gtk-cancel"/>
- <button string="Request Re-activation" name="get_reapprove" states="suspended" type="workflow" icon="gtk-convert"/>
- <button string="Send/Receive" name="send_receive" states="approved" type="object" icon="terp-check"/>
- </group>
- </form>
- </field>
- </record>
-
- <record model="ir.ui.view" id="email_template_account_tree">
- <field name="name">email_template.account.tree</field>
- <field name="model">email_template.account</field>
- <field name="type">tree</field>
- <field name="arch" type="xml">
- <tree colors="blue:state == 'draft';black:state in ('suspended','approved')" string="Email Accounts">
- <field name="name" />
- <field name="email_id" />
- <field name="smtpuname" />
- <field name="user" />
- <field name="smtpserver" />
- <field name="smtpport" />
- <field name="auto_delete" />
- <field name="state" />
- </tree>
- </field>
- </record>
-
- <record id="view_email_template_account_search" model="ir.ui.view">
- <field name="name">email_template.account.search</field>
- <field name="model">email_template.account</field>
- <field name="type">search</field>
- <field name="arch" type="xml">
- <search string="Email Accounts">
- <filter icon="terp-document-new" string="Draft" name="draft" domain="[('state','=','draft')]"/>
- <filter icon="terp-camera_test" string="Approved" domain="[('state','=','approved')]"/>
- <filter icon="terp-emblem-important" string="Suspended" domain="[('state','=','suspended')]"/>
- <separator orientation="vertical"/>
- <filter icon="terp-go-home" string="Company Accounts" domain="[('company','=','yes')]"/>
- <separator orientation="vertical"/>
- <field name="user" select="1">
- <filter icon="terp-personal" help="My Accounts" name="my" domain="[('user','=',uid)]"/>
- </field>
- <field name="name" select="1"/>
- <field name="email_id" select="1"/>
- </search>
- </field>
- </record>
-
- <record model="ir.actions.act_window" id="action_email_template_account_tree_all">
- <field name="name">Accounts</field>
- <field name="res_model">email_template.account</field>
- <field name="view_type">form</field>
- <field name="view_mode">form,tree</field>
- <field name="view_id" ref="email_template_account_tree" />
- <field name="context">{'search_default_draft': 1, 'search_default_my': 1}</field>
- <field name="search_view_id" ref="view_email_template_account_search"/>
- </record>
-
- <menuitem name="Configuration" parent="base.marketing_menu"
- id="base.menu_marketing_config_root" sequence="20" groups="base.group_system"/>
-
- <menuitem name="Email Template" id="menu_email_template_configuration" parent="base.menu_marketing_config_root" />
-
- <menuitem name="Email Accounts" id="menu_email_template_account_all" parent="menu_email_template_configuration" action="action_email_template_account_tree_all"/>
-
- <menuitem name="Configuration" parent="base.menu_tools"
- id="base.menu_lunch_survey_root" sequence="20" />
-
- <menuitem name="Email Template" id="menu_email_template_config_tools"
- parent="base.menu_lunch_survey_root" />
-
- <menuitem name="Email Accounts" id="menu_email_account_all_tools"
- parent="menu_email_template_config_tools" action="action_email_template_account_tree_all" />
-
- </data>
-</openerp>
-
-
-
-
diff --git a/addons/email_template/email_template_mailbox.py b/addons/email_template/email_template_mailbox.py
deleted file mode 100644
index 4486cb5451e..00000000000
--- a/addons/email_template/email_template_mailbox.py
+++ /dev/null
@@ -1,214 +0,0 @@
-# -*- coding: utf-8 -*-
-##############################################################################
-#
-# OpenERP, Open Source Management Solution
-# Copyright (C) 2009 Sharoon Thomas
-# Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>
-#
-##############################################################################
-
-from osv import osv, fields
-import time
-import netsvc
-from tools.translate import _
-import tools
-
-LOGGER = netsvc.Logger()
-
-class email_template_mailbox(osv.osv):
- _name = "email_template.mailbox"
- _description = 'Email Mailbox'
- _rec_name = "subject"
- _order = "date_mail desc"
-
- def run_mail_scheduler(self, cursor, user, context=None):
- """
- This method is called by OpenERP Scheduler
- to periodically send emails
- """
- try:
- self.send_all_mail(cursor, user, context=context)
- except Exception, e:
- LOGGER.notifyChannel(
- "Email Template",
- netsvc.LOG_ERROR,
- _("Error sending mail: %s") % e)
-
- def send_all_mail(self, cr, uid, ids=None, context=None):
- if ids is None:
- ids = []
- if context is None:
- context = {}
- filters = [('folder', '=', 'outbox'), ('state', '!=', 'sending')]
- if 'filters' in context.keys():
- for each_filter in context['filters']:
- filters.append(each_filter)
- ids = self.search(cr, uid, filters, context=context)
- self.write(cr, uid, ids, {'state':'sending'}, context)
- self.send_this_mail(cr, uid, ids, context)
- return True
-
- def send_this_mail(self, cr, uid, ids=None, context=None):
- #previous method to send email (link with email account can be found at the revision 4172 and below
- result = True
- attachment_pool = self.pool.get('ir.attachment')
- for id in (ids or []):
- try:
- account_obj = self.pool.get('email_template.account')
- values = self.read(cr, uid, id, [], context)
- payload = {}
- if values['attachments_ids']:
- for attid in values['attachments_ids']:
- attachment = attachment_pool.browse(cr, uid, attid, context)#,['datas_fname','datas'])
- payload[attachment.datas_fname] = attachment.datas
- result = account_obj.send_mail(cr, uid,
- [values['account_id'][0]],
- {'To':values.get('email_to') or u'',
- 'CC':values.get('email_cc') or u'',
- 'BCC':values.get('email_bcc') or u'',
- 'Reply-To':values.get('reply_to') or u''},
- values['subject'] or u'',
- {'text':values.get('body_text') or u'', 'html':values.get('body_html') or u''},
- payload=payload,
- message_id=values['message_id'],
- context=context)
- if result == True:
- account = account_obj.browse(cr, uid, values['account_id'][0], context=context)
- if account.auto_delete:
- self.write(cr, uid, id, {'folder': 'trash'}, context=context)
- self.unlink(cr, uid, [id], context=context)
- # Remove attachments for this mail
- attachment_pool.unlink(cr, uid, values['attachments_ids'], context=context)
- return result
- else:
- self.write(cr, uid, id, {'folder':'sent', 'state':'na', 'date_mail':time.strftime("%Y-%m-%d %H:%M:%S")}, context)
- self.historise(cr, uid, [id], "Email sent successfully", context)
- else:
- error = result['error_msg']
- self.historise(cr, uid, [id], error, context)
-
- except Exception, error:
- logger = netsvc.Logger()
- logger.notifyChannel("email-template", netsvc.LOG_ERROR, _("Sending of Mail %s failed. Probable Reason:Could not login to server\nError: %s") % (id, error))
- self.historise(cr, uid, [id], error, context)
- self.write(cr, uid, id, {'state':'na'}, context)
- return result
-
- def historise(self, cr, uid, ids, message='', context=None):
- for id in ids:
- history = self.read(cr, uid, id, ['history'], context).get('history', '')
- self.write(cr, uid, id, {'history': (history or '' )+ "\n" + time.strftime("%Y-%m-%d %H:%M:%S") + ": " + tools.ustr(message)}, context)
-
- _columns = {
- 'email_from':fields.char(
- 'From',
- size=64),
- 'email_to':fields.char(
- 'Recipient (To)',
- size=250,),
- 'email_cc':fields.char(
- 'CC',
- size=250),
- 'email_bcc':fields.char(
- 'BCC',
- size=250),
- 'reply_to':fields.char(
- 'Reply-To',
- size=250),
- 'message_id':fields.char(
- 'Message-ID',
- size=250),
- 'subject':fields.char(
- 'Subject',
- size=200,),
- 'body_text':fields.text(
- 'Standard Body (Text)'),
- 'body_html':fields.text(
- 'Body (Rich Text Clients Only)'),
- 'attachments_ids':fields.many2many(
- 'ir.attachment',
- 'mail_attachments_rel',
- 'mail_id',
- 'att_id',
- 'Attachments'),
- 'account_id' :fields.many2one(
- 'email_template.account',
- 'User account',
- required=True),
- 'user':fields.related(
- 'account_id',
- 'user',
- type="many2one",
- relation="res.users",
- string="User"),
- 'server_ref':fields.integer(
- 'Server Reference of mail',
- help="Applicable for inward items only"),
- 'mail_type':fields.selection([
- ('multipart/mixed',
- 'Has Attachments'),
- ('multipart/alternative',
- 'Plain Text & HTML with no attachments'),
- ('multipart/related',
- 'Intermixed content'),
- ('text/plain',
- 'Plain Text'),
- ('text/html',
- 'HTML Body'),
- ], 'Mail Contents'),
- #I like GMAIL which allows putting same mail in many folders
- #Lets plan it for 0.9
- 'folder':fields.selection([
- ('drafts', 'Drafts'),
- ('outbox', 'Outbox'),
- ('trash', 'Trash'),
- ('sent', 'Sent Items'),
- ], 'Folder', required=True),
- 'state':fields.selection([
- ('na', 'Not Applicable'),
- ('sending', 'Sending'),
- ], 'Status', required=True),
- 'date_mail':fields.datetime('Rec/Sent Date', help="Date on which Email Sent or Received"),
- 'history':fields.text(
- 'History',
- readonly=True,
- store=True)
- }
-
- _defaults = {
- 'state': lambda * a: 'na',
- 'folder': lambda * a: 'outbox',
- }
-
- def unlink(self, cr, uid, ids, context=None):
- """
- It just changes the folder of the item to "Trash", if it is no in Trash folder yet,
- or completely deletes it if it is already in Trash.
- """
- to_update = []
- to_remove = []
- for mail in self.browse(cr, uid, ids, context=context):
- if mail.folder == 'trash':
- to_remove.append(mail.id)
- else:
- to_update.append(mail.id)
- # Changes the folder to trash
- self.write(cr, uid, to_update, {'folder': 'trash'}, context=context)
- return super(email_template_mailbox, self).unlink(cr, uid, to_remove, context=context)
-
-email_template_mailbox()
-
-# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diff --git a/addons/email_template/email_template_mailbox_view.xml b/addons/email_template/email_template_mailbox_view.xml
deleted file mode 100644
index 0d1b3b0a2bf..00000000000
--- a/addons/email_template/email_template_mailbox_view.xml
+++ /dev/null
@@ -1,134 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<openerp>
- <data>
- <!-- Email Template-->
- <record model="ir.ui.view" id="email_template_mailbox_form">
- <field name="name">email_template.mailbox.form</field>
- <field name="model">email_template.mailbox</field>
- <field name="type">form</field>
- <field name="arch" type="xml">
- <form string="Emails">
- <group col="4" colspan="4" name="headers">
- <field name="email_from" select="1"/>
- <field name="email_to" required="1" select="1" />
- <field name="reply_to" select="2"/>
- <field name="email_cc" select="1"/>
- <field name="email_bcc" select="2"/>
- <field name="date_mail" select="2"/>
- <field name="subject" colspan="4" select="1"/>
- </group>
- <notebook colspan="4">
- <page string="Standard Body">
- <separator colspan="4" string="Standard Body" />
- <notebook colspan="4">
- <page string="Standard Body (Text)">
- <field name="body_text" nolabel="1" colspan="4" select="1"/>
- </page>
- <page string="Body (HTML-Web Client Only)">
- <field name="body_html" nolabel="1" colspan="4" />
- </page>
- </notebook>
- <separator colspan="4" string="" />
- <group col="4" colspan="4">
- <field name="state" readonly="1" string="State"/>
- <button name="send_this_mail" type="object" string="Send Mail" icon="terp-mail-message-new"/>
- </group>
- </page>
-
- <page string="Attachments">
- <separator colspan="4" string="Attachments" />
- <field name="attachments_ids" colspan="4" nolabel="1" />
- </page>
- <page string="Advanced">
- <field name="account_id" colspan="2" />
- <field name="server_ref" colspan="2" />
- <field name="mail_type" colspan="2" />
- <field name="folder" colspan="2" select="2"/>
- <field name="message_id" select="2"/>
- <separator string="History" colspan="4" />
- <field name="history" nolabel="1" colspan="4"/>
- </page>
- </notebook>
- </form>
- </field>
- </record>
-
- <!--============================================= TREE VIEWS =============================================-->
- <record id="view_email_template_mailbox_tree" model="ir.ui.view">
- <field name="name">email_template.mailbox.tree</field>
- <field name="model">email_template.mailbox</field>
- <field name="type">tree</field>
- <field name="arch" type="xml">
- <tree string="Emails" colors="blue:folder=='drafts';grey:folder=='trash'">
- <field name="subject" select="1" />
- <field name="user" />
- <field name="email_from" select="1" />
- <field name="email_to"/>
- <field name="date_mail" select="2" />
- <field name="attachments_ids" select="2" />
- <field name="folder" invisible="1"/>
- </tree>
- </field>
- </record>
-
- <record id="view_email_template_mailbox_search" model="ir.ui.view">
- <field name="name">email_template.mailbox.search</field>
- <field name="model">email_template.mailbox</field>
- <field name="type">search</field>
- <field name="arch" type="xml">
- <search string="Emails">
- <filter icon="terp-document-new" string="Drafts" name="draft" domain="[('folder','=','drafts')]"/>
- <filter icon="terp-mail-" string="Outbox" name="outbox" domain="[('folder','=','outbox')]"/>
- <filter icon="terp-camera_test" string="Sent" domain="[('folder','=','sent')]"/>
- <filter icon="terp-mail_delete" string="Trash" domain="[('folder','=','trash')]"/>
- <separator orientation="vertical"/>
- <filter icon="terp-personal+" string="Personal Emails" name="personal" domain="[('account_id.company','=','no')]"/>
- <filter icon="terp-go-home" string="Company Emails" name="company" domain="[('account_id.company','=','yes')]"/>
- <separator orientation="vertical"/>
- <field name="subject"/>
- <field name="email_from"/>
- <field name="user">
- <filter icon="terp-personal"
- string="My Emails" help="My Emails" name="myemails"
- domain="[('account_id.user','=', uid)]" />
- </field>
- <newline/>
- <field name="email_to"/>
- <field name="date_mail"/>
- </search>
- </field>
- </record>
-
- <record model="ir.actions.act_window" id="action_email_template_mailbox">
- <field name="name">Emails</field>
- <field name="res_model">email_template.mailbox</field>
- <field name="view_type">form</field>
- <field name="view_mode">tree,form</field>
- <field name="view_id" ref="view_email_template_mailbox_tree" />
- <field name="context">{'search_default_outbox': 1}</field>
- <field name="help">An email template is an email document that will be sent as part of a marketing campaign. You can personalize it according to specific customer profile fields, so that a partner name or other partner related information may be inserted automatically.</field>
- <field name="search_view_id" ref="view_email_template_mailbox_search"/>
- </record>
-
- <!--======================================== MENUS ========================================-->
-
- <menuitem name="Emails"
- id="menu_email_template_personal_mails"
- parent="menu_email_template"
- action="action_email_template_mailbox" />
-
- <!-- Mailbox menu in Tools -->
- <menuitem name="Email Template" id="menu_email_template_tools"
- parent="base.menu_tools" />
-
- <menuitem name="Emails"
- id="menu_email_template_mails_tools"
- parent="menu_email_template_tools"
- action="action_email_template_mailbox" />
-
- </data>
-</openerp>
-
-
-
-
diff --git a/addons/email_template/email_template_scheduler_data.xml b/addons/email_template/email_template_scheduler_data.xml
deleted file mode 100644
index 45a9be04ac7..00000000000
--- a/addons/email_template/email_template_scheduler_data.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<openerp>
- <data noupdate="1">
- <record forcecreate="True" id="ir_cron_mail_scheduler_action" model="ir.cron">
- <field name="name">Email Template scheduler</field>
- <field name="user_id" ref="base.user_root"/>
- <field name="interval_number">1</field>
- <field name="interval_type">hours</field>
- <field name="numbercall">-1</field>
- <field eval="False" name="doall"/>
- <field eval="'email_template.mailbox'" name="model"/>
- <field eval="'run_mail_scheduler'" name="function"/>
- <field eval="'()'" name="args"/>
- </record>
- </data>
-</openerp>
diff --git a/addons/email_template/email_template_view.xml b/addons/email_template/email_template_view.xml
index 7d2a5f7ad5c..b4f76a03c6c 100644
--- a/addons/email_template/email_template_view.xml
+++ b/addons/email_template/email_template_view.xml
@@ -1,141 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<openerp>
<data>
-
- <!-- Email Template Preview -->
- <record model="ir.ui.view" id="email_template_preview_form">
- <field name="name">email_template.preview.form</field>
- <field name="model">email_template.preview</field>
- <field name="type">form</field>
- <field name="arch" type="xml">
- <form string="Email Preview">
- <group col="4" colspan="4">
- <field name="rel_model" />
- <field name="rel_model_ref" on_change="on_change_ref(rel_model_ref, context)"/>
- </group>
- <group col="8" colspan="4">
- <field name="to" />
- <field name="cc" />
- <field name="bcc" />
- <field name="reply_to" />
- <field name="message_id" attrs="{'invisible':[('message_id','=',False)]}" groups="base.group_extended"/>
- <field name="subject" colspan="8"/>
- </group>
- <group col="4" colspan="4">
- <separator string= "Body(Text)" colspan="2"/>
- <separator string= "Body(Html)" colspan="2"/>
- <newline/>
- <field name="body_text" nolabel="1" colspan="2"/>
- <field name="body_html" nolabel="1" colspan="2"/>
- </group>
- <field name="report" colspan="2"/>
- <button icon="gtk-ok" special="cancel" string="OK" colspan="1"/>
- </form>
- </field>
- </record>
-
- <record id="wizard_email_template_preview" model="ir.actions.act_window">
- <field name="name">Template Preview</field>
- <field name="res_model">email_template.preview</field>
- <field name="src_model">email_template.preview</field>
- <field name="type">ir.actions.act_window</field>
- <field name="view_type">form</field>
- <field name="view_mode">form</field>
- <field name="auto_refresh" eval="1" />
- <field name="target">new</field>
- <field name="context">{'template_id':active_id}</field>
- </record>
- <!--EMail client Form view -->
<record model="ir.ui.view" id="email_template_form">
<field name="name">email.template.form</field>
<field name="model">email.template</field>
<field name="type">form</field>
<field name="arch" type="xml">
- <form string="Email Templates">
- <field name="name" />
- <field name="object_name" required="1"
- on_change="change_model(object_name)" />
- <field name="model_int_name" invisible="1" />
+ <form string="Templates">
+ <field name="name" required="1"/>
+ <field name="model_id" required="1" on_change="onchange_model_id(model_id)"/>
+ <field name="model" invisible="1"/>
<notebook colspan="4">
- <page string="Mail Details">
+ <page string="Email Details">
<group col="2" colspan="2">
<separator string="Addresses" colspan="2"/>
- <field name="from_account" required="1"/>
- <field name="def_to" required="1"/>
- <field name="def_cc"/>
- <field name="def_bcc"/>
+ <field name="email_from" required="1"/>
+ <field name="email_to" required="1"/>
+ <field name="email_cc"/>
+ <field name="email_bcc"/>
<field name="reply_to"/>
</group>
<group col="2" colspan="2">
<separator string="Options" colspan="2"/>
<field name="lang" colspan="4" />
- <field name="use_sign" colspan="4" />
- <field name="track_campaign_item" colspan="4"/>
+ <field name="user_signature" colspan="4" />
</group>
<group col="2" colspan="2">
- <separator colspan="2" string="Email Content " />
- <field name="def_subject" colspan="4" required="1" />
+ <separator colspan="2" string="Email Content"/>
+ <field name="subject" colspan="4" required="1"/>
<notebook>
<page string="Body (Text)">
- <field name="def_body_text" colspan="4" nolabel="1" />
+ <field name="body_text" colspan="4" width="250" height="250" nolabel="1"/>
</page>
- <page string="Body (Raw HTML)">
- <field name="def_body_html" colspan="4" nolabel="1" />
- <label string="Note: This is Raw HTML." colspan="4" />
+ <page string="Body (Rich/HTML)">
+ <field name="body_html" colspan="4" width="250" height="250" nolabel="1"/>
+ <label string="Note: This is Raw HTML." colspan="4"/>
</page>
</notebook>
</group>
<group col="4" colspan="2">
- <separator colspan="4" string="Expression Builder" />
- <field name="template_language"
- on_change="onchange_null_value(model_object_field,sub_model_object_field,null_value,template_language,context)" />
<notebook>
- <page string="Insert Simple Field">
-
+ <page string="Dynamic Values Builder">
<field name="model_object_field"
- domain="[('model_id','=',object_name),('ttype','!=','one2many'),('ttype','!=','many2many')]"
- on_change="onchange_model_object_field(model_object_field, template_language,context)"
- colspan="4" />
- <field name="sub_object" readonly="1" colspan="4" />
+ domain="[('model_id','=',model_id),('ttype','!=','one2many'),('ttype','!=','many2many')]"
+ on_change="onchange_sub_model_object_value_field(model_object_field)"
+ colspan="4"/>
+ <field name="sub_object" readonly="1" colspan="4"/>
<field name="sub_model_object_field"
domain="[('model_id','=',sub_object),('ttype','!=','one2many'),('ttype','!=','many2many')]"
colspan="4"
attrs="{'readonly':[('sub_object','=',False)],'required':[('sub_object','!=',False)]}"
- on_change="onchange_sub_model_object_field(model_object_field,sub_model_object_field,template_language,context)" />
+ on_change="onchange_sub_model_object_value_field(model_object_field,sub_model_object_field)"/>
<field name="null_value" colspan="4"
- on_change="onchange_null_value(model_object_field,sub_model_object_field,null_value,template_language,context)" />
- <field name="copyvalue" colspan="4" />
+ on_change="onchange_sub_model_object_value_field(model_object_field,sub_model_object_field,null_value)" />
+ <field name="copyvalue" colspan="4"/>
</page>
</notebook>
<button name="%(wizard_email_template_preview)d" string="Preview Template"
- type="action" colspan="4" target="new" icon="gtk-zoom-fit"/>
+ type="action" colspan="4" target="new" icon="gtk-zoom-fit" context="{'template_id':active_id}"/>
</group>
</page>
<page string="Advanced">
<group colspan="2" col="2">
<group colspan="2" col="2">
- <separator string="Actions" colspan="2"/>
- <button name="create_action" string="Create Action" type="object" icon="gtk-execute" colspan="2" attrs="{'invisible':[('ref_ir_act_window','!=',False), ('ref_ir_value','!=',False)]}"/>
- <field name="ref_ir_act_window"/>
- <field name="ref_ir_value"/>
- <button name="delete_action" string="Delete Action" type="object" icon="gtk-delete" colspan="2" attrs="{'invisible':[('ref_ir_act_window','=',False), ('ref_ir_value','=',False)]}"/>
+ <separator string="Sidebar button" colspan="2"/>
+ <button name="create_action" string="Add sidebar button" type="object" icon="gtk-execute"
+ colspan="2" attrs="{'invisible':[('ref_ir_act_window','!=',False)]}"
+ help="Display a button in the sidebar of related documents to open a composition wizard with this template"
+ />
+ <field name="ref_ir_act_window" attrs="{'invisible':[('ref_ir_act_window','=',False)]}"/>
+ <field name="ref_ir_value" attrs="{'invisible':[('ref_ir_act_window','=',False)]}"/>
+ <button name="unlink_action" string="Remove sidebar button" type="object" icon="gtk-delete"
+ colspan="2" attrs="{'invisible':[('ref_ir_act_window','=',False)]}"
+ help="Remove the sidebar button currently displayed on related documents"
+ />
</group>
- <group colspan="2" col="2">
+ <group colspan="2" col="2" groups="base.group_extended">
<separator string="Advanced Options" colspan="2"/>
+ <field name="mail_server_id"/>
+ <field name="track_campaign_item" colspan="4"/>
<field name="message_id"/>
+ <field name="auto_delete"/>
</group>
</group>
<group colspan="2" col="2">
<separator string="Attachments" colspan="2"/>
<notebook>
- <page string="Existing files">
- <field name="attachment_ids" colspan="4" nolabel="1" height="350"/>
- </page>
- <page string="Report">
+ <page string="Attach Report">
<field name="report_template" colspan="4"
- domain="[('model','=',model_int_name)]" />
- <field name="file_name" colspan="4" />
+ domain="[('model','=',model)]"/>
+ <field name="report_name" colspan="4" />
+ </page>
+ <page string="Attach existing files">
+ <field name="attachment_ids" colspan="4" nolabel="1" height="350"/>
</page>
</notebook>
</group>
@@ -150,16 +108,13 @@
<field name="model">email.template</field>
<field name="type">tree</field>
<field name="arch" type="xml">
- <tree string="Email Templates">
+ <tree string="Templates">
+ <field name="model_id"/>
<field name="name"/>
- <field name="from_account"/>
- <field name="object_name"/>
- <field name="def_to"/>
- <field name="def_cc"/>
- <field name="def_bcc"/>
- <field name="def_subject"/>
- <field name="use_sign"/>
- <field name="file_name"/>
+ <field name="subject"/>
+ <field name="email_from"/>
+ <field name="email_to"/>
+ <field name="report_name"/>
<button name="%(wizard_email_template_preview)d" string="Preview Template"
type="action" target="new" icon="gtk-zoom-fit"/>
</tree>
@@ -173,26 +128,26 @@
<field name="arch" type="xml">
<search string="Templates">
<group col="13" colspan="4">
- <field name="name" select="1"/>
- <field name="object_name" select="1"/>
- <field name="def_to" select="1"/>
+ <field name="name"/>
+ <field name="model_id"/>
+ <field name="email_to"/>
<separator orientation="vertical"/>
- <field name="lang" select="1"/>
- <field name="def_subject" select="1"/>
- <field name="file_name" select="1"/>
+ <field name="lang"/>
+ <field name="subject"/>
+ <field name="report_name"/>
</group>
<newline/>
<group expand="0" string="Group by..." colspan="4" col="10">
- <filter string="Account" domain="[]" context="{'group_by':'from_account'}" icon="terp-folder-orange"/>
+ <filter string="SMTP Server" domain="[]" context="{'group_by':'smtp_server_id'}" icon="terp-folder-orange"/>
<separator orientation="vertical"/>
- <filter string="Resource" domain="[]" context="{'group_by':'object_name'}" icon="terp-accessories-archiver"/>
+ <filter string="Model" domain="[]" context="{'group_by':'model_id'}" icon="terp-accessories-archiver"/>
</group>
</search>
</field>
</record>
<record model="ir.actions.act_window" id="action_email_template_tree_all">
- <field name="name">Email Templates</field>
+ <field name="name">Templates</field>
<field name="res_model">email.template</field>
<field name="view_type">form</field>
<field name="view_mode">form,tree</field>
@@ -200,16 +155,9 @@
<field name="search_view_id" ref="view_email_template_search"/>
</record>
- <menuitem name="Email Templates" id="menu_email_template_all"
- parent="menu_email_template" action="action_email_template_tree_all" />
+ <menuitem name="Templates" id="menu_email_template_all_tools"
+ parent="mail.menu_email_message_tools" action="action_email_template_tree_all" />
+
- <!-- Email Template menu in Tools -->
- <menuitem name="Email Templates" id="menu_email_template_all_tools"
- parent="menu_email_template_config_tools" action="action_email_template_tree_all" />
</data>
</openerp>
-
-
-
-
-
diff --git a/addons/email_template/email_template_workflow.xml b/addons/email_template/email_template_workflow.xml
deleted file mode 100644
index 84a58815b5e..00000000000
--- a/addons/email_template/email_template_workflow.xml
+++ /dev/null
@@ -1,64 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<openerp>
- <data>
-
- <record id="wkf_email_template_setting" model="workflow">
- <field name="name">Email Template Workflow</field>
- <field name="osv">email_template.account</field>
- <field name="on_create">True</field>
- </record>
-
- <!--Activity -->
-
- <record id="act_draft" model="workflow.activity">
- <field name="wkf_id" ref="wkf_email_template_setting"/>
- <field name="flow_start">True</field>
- <field name="name">draft</field>
- <field name="kind">function</field>
- <field name="action">write({'state':'draft'})</field>
- </record>
-
- <record id="act_approved" model="workflow.activity">
- <field name="name">approval</field>
- <field name="wkf_id" ref="wkf_email_template_setting"/>
- <field name="kind">function</field>
- <field name="action">do_approval()</field>
- </record>
-
- <record id="act_suspended" model="workflow.activity">
- <field name="name">suspended</field>
- <field name="wkf_id" ref="wkf_email_template_setting"/>
- <field name="kind">function</field>
- <field name="action">write({'state':'suspended'})</field>
- </record>
- <record id="act_dummy" model="workflow.activity">
- <field name="name">dummy</field>
- <field name="wkf_id" ref="wkf_email_template_setting"/>
- <field name="flow_stop">True</field>
- </record>
-
- <!-- Transition -->
-
- <record id="trans_awaiting_approved" model="workflow.transition">
- <field name="act_from" ref="act_draft"/>
- <field name="act_to" ref="act_approved"/>
- <field name="signal">button_approval</field>
- </record>
-
- <record id="trans_approved_suspended" model="workflow.transition">
- <field name="act_from" ref="act_approved"/>
- <field name="act_to" ref="act_suspended"/>
- <field name="signal">button_suspended</field>
- </record>
- <record id="trans_suspended_reapproved" model="workflow.transition">
- <field name="act_from" ref="act_suspended"/>
- <field name="act_to" ref="act_draft"/>
- <field name="signal">get_reapprove</field>
- </record>
- <record id="trans_suspended_dummy" model="workflow.transition">
- <field name="act_from" ref="act_suspended"/>
- <field name="act_to" ref="act_dummy"/>
- <field name="signal">get_never</field>
- </record>
- </data>
-</openerp>
diff --git a/addons/email_template/security/email_template_security.xml b/addons/email_template/security/email_template_security.xml
deleted file mode 100644
index e3f3401217c..00000000000
--- a/addons/email_template/security/email_template_security.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<openerp>
- <data noupdate="0">
-
- </data>
-</openerp>
diff --git a/addons/email_template/security/ir.model.access.csv b/addons/email_template/security/ir.model.access.csv
index 17859d6bb9d..f5f61240a96 100644
--- a/addons/email_template/security/ir.model.access.csv
+++ b/addons/email_template/security/ir.model.access.csv
@@ -1,10 +1,4 @@
"id","name","model_id:id","group_id:id","perm_read","perm_write","perm_create","perm_unlink"
-"access_email_template_account","email_template.account","model_email_template_account","marketing.group_marketing_user",1,0,0,0
-"access_email_template","email.template","model_email_template","marketing.group_marketing_user",1,0,0,0
-"access_email_template_mailbox","email_template.mailbox","model_email_template_mailbox","marketing.group_marketing_user",1,1,1,1
-"access_email_template_account_system","email_template.account system","model_email_template_account","base.group_system",1,1,1,1
+"access_email_template","email.template","model_email_template",,1,0,0,0
"access_email_template_system","email.template system","model_email_template","base.group_system",1,1,1,1
-"access_email_template_mailbox_system","email_template.mailbox system","model_email_template_mailbox","base.group_system",1,0,0,0
-"access_email_template_account_manager","email_template.account","model_email_template_account","marketing.group_marketing_manager",1,1,1,1
-"access_email_template_manager","email.template","model_email_template","marketing.group_marketing_manager",1,1,1,1
-"access_email_template_mailbox_manager","email_template.mailbox","model_email_template_mailbox","marketing.group_marketing_manager",1,1,1,1
+"access_email_template_manager","email.template","model_email_template",,1,1,1,1
diff --git a/addons/email_template/wizard/__init__.py b/addons/email_template/wizard/__init__.py
index 1641152490e..b9ac29ec4c2 100644
--- a/addons/email_template/wizard/__init__.py
+++ b/addons/email_template/wizard/__init__.py
@@ -3,7 +3,7 @@
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2009 Sharoon Thomas
-# Copyright (C) 2010-2010 OpenERP SA (<http://www.openerp.com>)
+# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -19,5 +19,6 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
##############################################################################
+import email_template_preview
+import mail_compose_message
-import email_template_send_wizard
diff --git a/addons/email_template/wizard/email_compose_message_view.xml b/addons/email_template/wizard/email_compose_message_view.xml
new file mode 100644
index 00000000000..cf233b20682
--- /dev/null
+++ b/addons/email_template/wizard/email_compose_message_view.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<openerp>
+ <data>
+
+ <record model="ir.ui.view" id="email_compose_message_wizard_inherit_form">
+ <field name="name">mail.compose.message.form</field>
+ <field name="model">mail.compose.message</field>
+ <field name="type">form</field>
+ <field name="inherit_id" ref="mail.email_compose_message_wizard_form"/>
+ <field name="arch" type="xml">
+ <data>
+ <xpath expr="//label[@name='placeholder']" position="before">
+ <group attrs="{'invisible':[('use_template','=',False)]}" colspan="4" col="4">
+ <field name="template_id" colspan="3"
+ on_change="on_change_template(use_template, template_id, email_from, email_to, context)"/>
+ <label string="" name="flexspace" colspan="1"/>
+ </group>
+ <group colspan="1" col="6">
+ <field name="use_template" invisible="1"/>
+ <button icon="gtk-paste" type="object" name="template_toggle"
+ string="" help="Use a message template" colspan="1"/>
+ <button icon="gtk-save" type="object" name="save_as_template"
+ string="" help="Save as a new template" colspan="1"/>
+ </group>
+ </xpath>
+ </data>
+ </field>
+ </record>
+ </data>
+</openerp>
diff --git a/addons/email_template/wizard/email_template_preview.py b/addons/email_template/wizard/email_template_preview.py
new file mode 100644
index 00000000000..650b714866d
--- /dev/null
+++ b/addons/email_template/wizard/email_template_preview.py
@@ -0,0 +1,93 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+# OpenERP, Open Source Management Solution
+# Copyright (C) 2009 Sharoon Thomas
+# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>
+#
+##############################################################################
+
+from osv import osv, fields
+
+class email_template_preview(osv.osv_memory):
+ _inherit = "email.template"
+ _name = "email_template.preview"
+ _description = "Email Template Preview"
+ _rec_name = "subject"
+
+ def _get_records(self, cr, uid, context=None):
+ """
+ Return Records of particular Email Template's Model
+ """
+ if context is None:
+ context = {}
+
+ template_id = context.get('template_id', False)
+ if not template_id:
+ return []
+ email_template = self.pool.get('email.template')
+ template = email_template.browse(cr, uid, int(template_id), context=context)
+ template_object = template.model_id
+ model = self.pool.get(template_object.model)
+ record_ids = model.search(cr, uid, [], 0, 10, 'id', context=context)
+ default_id = context.get('default_res_id')
+
+ if default_id and default_id not in record_ids:
+ record_ids.insert(0, default_id)
+
+ return model.name_get(cr, uid, record_ids, context)
+
+
+ def default_get(self, cr, uid, fields, context=None):
+ if context is None:
+ context = {}
+ result = super(email_template_preview, self).default_get(cr, uid, fields, context=context)
+
+ email_template = self.pool.get('email.template')
+ template_id = context.get('template_id')
+ if 'res_id' in fields and not result.get('res_id'):
+ records = self._get_records(cr, uid, context=context)
+ result['res_id'] = records and records[0][0] or False # select first record as a Default
+ if template_id and 'model_id' in fields and not result.get('model_id'):
+ result['model_id'] = email_template.read(cr, uid, int(template_id), ['model_id'], context).get('model_id', False)
+ return result
+
+ _columns = {
+ 'res_id':fields.selection(_get_records, 'Sample Document'),
+ }
+
+ def on_change_res_id(self, cr, uid, ids, res_id, context=None):
+ if not res_id:
+ return {}
+ vals = {}
+ email_template = self.pool.get('email.template')
+ template_id = context and context.get('template_id')
+ template = email_template.get_email_template(cr, uid, template_id=template_id, record_id=res_id, context=context)
+ model = template.model
+ vals['email_to'] = self.render_template(cr, uid, template.email_to, model, res_id, context)
+ vals['email_cc'] = self.render_template(cr, uid, template.email_cc, model, res_id, context)
+ vals['email_bcc'] = self.render_template(cr, uid, template.email_bcc, model, res_id, context)
+ vals['reply_to'] = self.render_template(cr, uid, template.reply_to, model, res_id, context)
+ vals['subject'] = self.render_template(cr, uid, template.subject, model, res_id, context)
+ description = self.render_template(cr, uid, template.body_text, model, res_id, context) or ''
+ if template.user_signature:
+ signature = self.pool.get('res.users').browse(cr, uid, uid, context).signature
+ description += '\n' + signature
+ vals['body_text'] = description
+ vals['report_name'] = self.render_template(cr, uid, template.report_name, model, res_id, context)
+ return {'value': vals}
+
+# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diff --git a/addons/email_template/wizard/email_template_preview_view.xml b/addons/email_template/wizard/email_template_preview_view.xml
new file mode 100644
index 00000000000..4aab57396ad
--- /dev/null
+++ b/addons/email_template/wizard/email_template_preview_view.xml
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="utf-8"?>
+<openerp>
+ <data>
+ <!-- Email Template Preview -->
+ <record model="ir.ui.view" id="email_template_preview_form">
+ <field name="name">email_template.preview.form</field>
+ <field name="model">email_template.preview</field>
+ <field name="type">form</field>
+ <field name="arch" type="xml">
+ <form string="Email Preview">
+ <field name="model_id" invisible="1"/>
+ <field name="res_id" on_change="on_change_res_id(res_id, context)"/>
+ <group col="2" colspan="4">
+ <field name="email_to" readonly="1"/>
+ <field name="email_cc" readonly="1" attrs="{'invisible': [('email_cc','=',False)]}"/>
+ <field name="email_bcc" readonly="1" attrs="{'invisible': [('email_bcc','=',False)]}"/>
+ <field name="reply_to" readonly="1" attrs="{'invisible': [('reply_to','=',False)]}"/>
+ <field name="subject" readonly="1"/>
+ </group>
+ <group col="4" colspan="4">
+ <notebook>
+ <page string="Body (Text)">
+ <field name="body_text" nolabel="1" colspan="4" height="350" width="350" readonly="1"/>
+ </page>
+ <page string="Body (Rich/HTML)" attrs="{'invisible': [('body_html','=', False)]}">
+ <field name="body_html" nolabel="1" colspan="4" height="350" width="350" readonly="1"/>
+ </page>
+ </notebook>
+ </group>
+ <field name="report_name" colspan="4" readonly="1"/>
+ <separator colspan="4"/>
+ <group col="4" colspan="4">
+ <label string=""/>
+ <button icon="gtk-ok" special="cancel" string="Close" colspan="1"/>
+ </group>
+ </form>
+ </field>
+ </record>
+
+ <record id="wizard_email_template_preview" model="ir.actions.act_window">
+ <field name="name">Template Preview</field>
+ <field name="res_model">email_template.preview</field>
+ <field name="src_model">email_template.preview</field>
+ <field name="type">ir.actions.act_window</field>
+ <field name="view_type">form</field>
+ <field name="view_mode">form</field>
+ <field name="auto_refresh" eval="1" />
+ <field name="target">new</field>
+ <field name="context">{'template_id':active_id}</field>
+ </record>
+
+ </data>
+</openerp>
diff --git a/addons/email_template/wizard/email_template_send_wizard.py b/addons/email_template/wizard/email_template_send_wizard.py
deleted file mode 100644
index 4f6ab7af381..00000000000
--- a/addons/email_template/wizard/email_template_send_wizard.py
+++ /dev/null
@@ -1,279 +0,0 @@
-# -*- coding: utf-8 -*-
-##############################################################################
-#
-# OpenERP, Open Source Management Solution
-# Copyright (C) 2009 Sharoon Thomas
-# Copyright (C) 2010-2010 OpenERP SA (<http://www.openerp.com>)
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>
-#
-##############################################################################
-
-from osv import osv, fields
-from mako.template import Template
-from mako import exceptions
-import netsvc
-import base64
-from tools.translate import _
-import tools
-from email_template.email_template import get_value
-
-
-## FIXME: this wizard duplicates a lot of features of the email template preview,
-## one of the 2 should inherit from the other!
-
-class email_template_send_wizard(osv.osv_memory):
- _name = 'email_template.send.wizard'
- _description = 'This is the wizard for sending mail'
- _rec_name = "subject"
-
- def _get_accounts(self, cr, uid, context=None):
- if context is None:
- context = {}
-
- template = self._get_template(cr, uid, context)
- if not template:
- return []
-
- logger = netsvc.Logger()
-
- if template.from_account:
- return [(template.from_account.id, '%s (%s)' % (template.from_account.name, template.from_account.email_id))]
- else:
- account_id = self.pool.get('email_template.account').search(cr,uid,[('company','=','no'),('user','=',uid)], context=context)
- if account_id:
- account = self.pool.get('email_template.account').browse(cr,uid,account_id, context)
- return [(r.id,r.name + " (" + r.email_id + ")") for r in account]
- else:
- logger.notifyChannel(_("email-template"), netsvc.LOG_ERROR, _("No personal email accounts are configured for you. \nEither ask admin to enforce an account for this template or get yourself a personal email account."))
- raise osv.except_osv(_("Missing mail account"),_("No personal email accounts are configured for you. \nEither ask admin to enforce an account for this template or get yourself a personal email account."))
-
- def get_value(self, cursor, user, template, message, context=None, id=None):
- """Gets the value of the message parsed with the content of object id (or the first 'src_rec_ids' if id is not given)"""
- if not message:
- return ''
- if not id:
- id = context['src_rec_ids'][0]
- return get_value(cursor, user, id, message, template, context)
-
- def _get_template(self, cr, uid, context=None):
- if context is None:
- context = {}
- if not 'template' in context and not 'template_id' in context:
- return None
- if 'template_id' in context.keys():
- template_ids = self.pool.get('email.template').search(cr, uid, [('id','=',context['template_id'])], context=context)
- elif 'template' in context.keys():
- # Old versions of email_template used the name of the template. This caused
- # problems when the user changed the name of the template, but we keep the code
- # for compatibility with those versions.
- template_ids = self.pool.get('email.template').search(cr, uid, [('name','=',context['template'])], context=context)
- if not template_ids:
- return None
-
- template = self.pool.get('email.template').browse(cr, uid, template_ids[0], context)
-
- lang = self.get_value(cr, uid, template, template.lang, context)
- if lang:
- # Use translated template if necessary
- ctx = context.copy()
- ctx['lang'] = lang
- template = self.pool.get('email.template').browse(cr, uid, template.id, ctx)
- return template
-
- def _get_template_value(self, cr, uid, field, context=None):
- if context is None:
- context = {}
- template = self._get_template(cr, uid, context)
- if not template:
- return False
- if len(context['src_rec_ids']) > 1: # Multiple Mail: Gets original template values for multiple email change
- return getattr(template, field)
- else: # Simple Mail: Gets computed template values
- return self.get_value(cr, uid, template, getattr(template, field), context)
-
- _columns = {
- 'state':fields.selection([
- ('single','Simple Mail Wizard Step 1'),
- ('multi','Multiple Mail Wizard Step 1'),
- ('done','Wizard Complete')
- ],'Status',readonly=True),
- 'ref_template':fields.many2one('email.template','Template',readonly=True),
- 'rel_model':fields.many2one('ir.model','Model',readonly=True),
- 'rel_model_ref':fields.integer('Referred Document',readonly=True),
- 'from':fields.selection(_get_accounts,'From Account',select=True),
- 'to':fields.char('To',size=250,required=True),
- 'cc':fields.char('CC',size=250,),
- 'bcc':fields.char('BCC',size=250,),
- 'reply_to':fields.char('Reply-To',
- size=250,
- help="The address recipients should reply to,"
- " if different from the From address."
- " Placeholders can be used here."),
- 'message_id':fields.char('Message-ID',
- size=250,
- help="The Message-ID header value, if you need to"
- "specify it, for example to automatically recognize the replies later."
- " Placeholders can be used here."),
- 'subject':fields.char('Subject',size=200),
- 'body_text':fields.text('Body',),
- 'body_html':fields.text('Body',),
- 'report':fields.char('Report File Name',size=100,),
- 'signature':fields.boolean('Attach my signature to mail'),
- #'filename':fields.text('File Name'),
- 'requested':fields.integer('No of requested Mails',readonly=True),
- 'generated':fields.integer('No of generated Mails',readonly=True),
- 'full_success':fields.boolean('Complete Success',readonly=True),
- 'attachment_ids': fields.many2many('ir.attachment','send_wizard_attachment_rel', 'wizard_id', 'attachment_id', 'Attachments'),
- }
-
- #FIXME: probably better by overriding default_get directly
- _defaults = {
- 'state': lambda self,cr,uid,ctx: len(ctx['src_rec_ids']) > 1 and 'multi' or 'single',
- 'rel_model': lambda self,cr,uid,ctx: self.pool.get('ir.model').search(cr,uid,[('model','=',ctx['src_model'])],context=ctx)[0],
- 'rel_model_ref': lambda self,cr,uid,ctx: ctx['active_id'],
- 'to': lambda self,cr,uid,ctx: self._get_template_value(cr, uid, 'def_to', ctx),
- 'cc': lambda self,cr,uid,ctx: self._get_template_value(cr, uid, 'def_cc', ctx),
- 'bcc': lambda self,cr,uid,ctx: self._get_template_value(cr, uid, 'def_bcc', ctx),
- 'subject':lambda self,cr,uid,ctx: self._get_template_value(cr, uid, 'def_subject', ctx),
- 'body_text':lambda self,cr,uid,ctx: self._get_template_value(cr, uid, 'def_body_text', ctx),
- 'body_html':lambda self,cr,uid,ctx: self._get_template_value(cr, uid, 'def_body_html', ctx),
- 'report': lambda self,cr,uid,ctx: self._get_template_value(cr, uid, 'file_name', ctx),
- 'signature': lambda self,cr,uid,ctx: self._get_template(cr, uid, ctx).use_sign,
- 'ref_template':lambda self,cr,uid,ctx: self._get_template(cr, uid, ctx).id,
- 'reply_to': lambda self,cr,uid,ctx: self._get_template_value(cr, uid, 'reply_to', ctx),
- 'reply_to': lambda self,cr,uid,ctx: self._get_template_value(cr, uid, 'reply_to', ctx),
- 'requested':lambda self,cr,uid,ctx: len(ctx['src_rec_ids']),
- 'full_success': False,
- 'attachment_ids': [],
- }
-
- def fields_get(self, cr, uid, fields=None, context=None, write_access=True):
- if context is None:
- context = {}
- result = super(email_template_send_wizard, self).fields_get(cr, uid, fields, context, write_access)
- if 'attachment_ids' in result and 'src_model' in context:
- result['attachment_ids']['domain'] = [('res_model','=',context['src_model']),('res_id','=',context['active_id'])]
- return result
-
- def sav_to_drafts(self, cr, uid, ids, context=None):
- if context is None:
- context = {}
- mailid = self.save_to_mailbox(cr, uid, ids, context=context)
- if self.pool.get('email_template.mailbox').write(cr, uid, mailid, {'folder':'drafts'}, context):
- return {'type':'ir.actions.act_window_close' }
-
- def send_mail(self, cr, uid, ids, context=None):
- if context is None:
- context = {}
- mailid = self.save_to_mailbox(cr, uid, ids, context)
- if self.pool.get('email_template.mailbox').write(cr, uid, mailid, {'folder':'outbox'}, context):
- return {'type':'ir.actions.act_window_close' }
-
- def get_generated(self, cr, uid, ids=None, context=None):
- if ids is None:
- ids = []
- if context is None:
- context = {}
- logger = netsvc.Logger()
- if context['src_rec_ids'] and len(context['src_rec_ids'])>1:
- #Means there are multiple items selected for email.
- mail_ids = self.save_to_mailbox(cr, uid, ids, context)
- if mail_ids:
- self.pool.get('email_template.mailbox').write(cr, uid, mail_ids, {'folder':'outbox'}, context)
- logger.notifyChannel("email-template", netsvc.LOG_INFO, _("Emails for multiple items saved in outbox."))
- self.write(cr, uid, ids, {
- 'generated':len(mail_ids),
- 'state':'done'
- }, context)
- else:
- raise osv.except_osv(_("Email Template"),_("Email sending failed for one or more objects."))
- return True
-
- def save_to_mailbox(self, cr, uid, ids, context=None):
- def get_end_value(id, value):
- if len(context['src_rec_ids']) > 1: # Multiple Mail: Gets value from the template
- return self.get_value(cr, uid, template, value, context, id)
- else:
- return value
-
- if context is None:
- context = {}
- mail_ids = []
- template = self._get_template(cr, uid, context)
- for id in context['src_rec_ids']:
- screen_vals = self.read(cr, uid, ids[0], [],context)
- account = self.pool.get('email_template.account').read(cr, uid, screen_vals['from'], context=context)
- vals = {
- 'email_from': tools.ustr(account['name']) + "<" + tools.ustr(account['email_id']) + ">",
- 'email_to': get_end_value(id, screen_vals['to']),
- 'email_cc': get_end_value(id, screen_vals['cc']),
- 'email_bcc': get_end_value(id, screen_vals['bcc']),
- 'subject': get_end_value(id, screen_vals['subject']),
- 'body_text': get_end_value(id, screen_vals['body_text']),
- 'body_html': get_end_value(id, screen_vals['body_html']),
- 'account_id': screen_vals['from'],
- 'state':'na',
- 'mail_type':'multipart/alternative' #Options:'multipart/mixed','multipart/alternative','text/plain','text/html'
- }
- if screen_vals['signature']:
- signature = self.pool.get('res.users').read(cr, uid, uid, ['signature'], context)['signature']
- if signature:
- vals['body_text'] = tools.ustr(vals['body_text'] or '') + signature
- vals['body_html'] = tools.ustr(vals['body_html'] or '') + signature
-
- attachment_ids = []
-
- #Create partly the mail and later update attachments
- mail_id = self.pool.get('email_template.mailbox').create(cr, uid, vals, context)
- mail_ids.append(mail_id)
- if template.report_template:
- reportname = 'report.' + self.pool.get('ir.actions.report.xml').read(cr, uid, template.report_template.id, ['report_name'], context)['report_name']
- data = {}
- data['model'] = self.pool.get('ir.model').browse(cr, uid, screen_vals['rel_model'], context).model
-
- # Ensure report is rendered using template's language
- ctx = context.copy()
- if template.lang:
- ctx['lang'] = self.get_value(cr, uid, template, template.lang, context, id)
- service = netsvc.LocalService(reportname)
- (result, format) = service.create(cr, uid, [id], data, ctx)
- attachment_id = self.pool.get('ir.attachment').create(cr, uid, {
- 'name': _('%s (Email Attachment)') % tools.ustr(vals['subject']),
- 'datas': base64.b64encode(result),
- 'datas_fname': tools.ustr(get_end_value(id, screen_vals['report']) or _('Report')) + "." + format,
- 'description': vals['body_text'] or _("No Description"),
- 'res_model': 'email_template.mailbox',
- 'res_id': mail_id
- }, context)
- attachment_ids.append( attachment_id )
-
- # Add document attachments
- for attachment_id in screen_vals.get('attachment_ids',[]):
- new_id = self.pool.get('ir.attachment').copy(cr, uid, attachment_id, {
- 'res_model': 'email_template.mailbox',
- 'res_id': mail_id,
- }, context)
- attachment_ids.append( new_id )
-
- if attachment_ids:
- self.pool.get('email_template.mailbox').write(cr, uid, mail_id, {
- 'attachments_ids': [[6, 0, attachment_ids]],
- 'mail_type': 'multipart/mixed'
- }, context)
-
- return mail_ids
-email_template_send_wizard()
-
-# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diff --git a/addons/email_template/wizard/email_template_send_wizard_view.xml b/addons/email_template/wizard/email_template_send_wizard_view.xml
deleted file mode 100644
index a5ad037aee6..00000000000
--- a/addons/email_template/wizard/email_template_send_wizard_view.xml
+++ /dev/null
@@ -1,63 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<openerp>
- <data>
-
- <record model="ir.ui.view" id="email_template_send_wizard_form">
- <field name="name">email_template.send.wizard.form</field>
- <field name="model">email_template.send.wizard</field>
- <field name="type">form</field>
- <field name="arch" type="xml">
- <form string="Send mail Wizard">
- <group col="4" colspan="4">
- <field name="rel_model" colspan="2" />
- <field name="from" required="1" colspan="2" />
- </group>
- <group col="4" colspan="4">
- <group col="6" colspan="4">
- <field name="to" select="1" colspan="4" />
- <newline />
- <field name="cc" select="2" colspan="4" />
- <newline />
- <field name="bcc" select="2" colspan="4" />
- <newline />
- <field name="subject" select="2" colspan="4" attrs="{'required':[('state','=','single')]}" />
- <newline />
- <field name="report" colspan="4" />
- </group>
- <separator string="" colspan="4" />
- <notebook colspan="4">
- <page string="Body (Plain Text)">
- <field name="body_text" select="2" colspan="4" nolabel="1" />
- </page>
- <page string="Body (HTML)">
- <field name="body_html" select="2" colspan="4" nolabel="1" />
- </page>
- <page string="Attachments">
- <label string="Add here all attachments of the current document you want to include in the Email." colspan="4"/>
- <field name="attachment_ids" colspan="4" nolabel="1"/>
- </page>
- </notebook>
- <field name="signature" colspan="4" />
- </group>
- <group col="4" colspan="4" attrs="{'invisible':[('state','!=','single')]}">
- <button icon="gtk-apply" name="sav_to_drafts" string="Save in Drafts" type="object" />
- <button icon="gtk-ok" name="send_mail" string="Send now" type="object" />
- <button icon="gtk-cancel" special="cancel" string="Discard Mail" />
- </group>
- <group col="4" colspan="4" attrs="{'invisible':[('state','=','single')]}">
- <label string="Tip: Multiple emails are sent in the same language (the first one is proposed). We suggest you send emails in groups according to language." colspan="4"/>
- <field name="requested" />
- <field name="generated" />
- <button icon="gtk-ok" name="get_generated" string="Send all mails" type="object" states="multi" colspan="2" />
- <button icon="gtk-cancel" special="cancel" string="Discard Mail" colspan="2" states="multi" />
- </group>
- <button icon="gtk-ok" special="cancel" string="Close" colspan="4" states="done" />
- <field name="state" />
- <newline />
- <label string="After clicking send all mails, mails will be sent to outbox and cleared in next Send/Recieve" colspan="4"/>
- </form>
- </field>
- </record>
- </data>
-</openerp>
-
diff --git a/addons/email_template/wizard/mail_compose_message.py b/addons/email_template/wizard/mail_compose_message.py
new file mode 100644
index 00000000000..60dd022c1b9
--- /dev/null
+++ b/addons/email_template/wizard/mail_compose_message.py
@@ -0,0 +1,156 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+# OpenERP, Open Source Management Solution
+# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>
+#
+##############################################################################
+
+import base64
+
+from osv import osv
+from osv import fields
+from tools.translate import _
+import tools
+
+
+def _reopen(self,res_id,model):
+ return {'type': 'ir.actions.act_window',
+ 'view_mode': 'form',
+ 'view_type': 'form',
+ 'res_id': res_id,
+ 'res_model': self._name,
+ 'target': 'new',
+
+ # save original model in context, otherwise
+ # it will be lost on the action's context switch
+ 'mail.compose.target.model': model,
+ }
+
+class mail_compose_message(osv.osv_memory):
+ _inherit = 'mail.compose.message'
+
+ def _get_templates(self, cr, uid, context=None):
+ """
+ Return Email Template of particular Model.
+ """
+ if context is None:
+ context = {}
+ record_ids = []
+ email_template= self.pool.get('email.template')
+ model = False
+ if context.get('message_id'):
+ mail_message = self.pool.get('mail.message')
+ message_data = mail_message.browse(cr, uid, int(context.get('message_id')), context)
+ model = message_data.model
+ elif context.get('mail.compose.target.model') or context.get('active_model'):
+ model = context.get('mail.compose.target.model', context.get('active_model'))
+ if model:
+ record_ids = email_template.search(cr, uid, [('model', '=', model)])
+ return email_template.name_get(cr, uid, record_ids, context) + [(False,'')]
+ return []
+
+ _columns = {
+ 'use_template': fields.boolean('Use Template'),
+ 'template_id': fields.selection(_get_templates, 'Template'),
+ }
+
+ def on_change_template(self, cr, uid, ids, use_template, template_id, email_from=None, email_to=None, context=None):
+ if context is None:
+ context = {}
+ values = {}
+ if template_id:
+ res_id = context.get('active_id', False)
+ if context.get('mail.compose.message.mode') == 'mass_mail':
+ # use the original template values - to be rendered when actually sent
+ # by super.send_mail()
+ values = self.pool.get('email.template').read(cr, uid, template_id, self.fields_get_keys(cr, uid), context)
+ else:
+ # render the mail as one-shot
+ values = self.pool.get('email.template').generate_email(cr, uid, template_id, res_id, context=context)
+ # retrofit generated attachments in the expected field format
+ if values['attachments']:
+ attachment = values.pop('attachments')
+ attachment_obj = self.pool.get('ir.attachment')
+ att_ids = []
+ for fname, fcontent in attachment.iteritems():
+ data_attach = {
+ 'name': fname,
+ 'datas': base64.b64encode(fcontent),
+ 'datas_fname': fname,
+ 'description': fname,
+ 'res_model' : self._name,
+ 'res_id' : ids[0] if ids else False
+ }
+ att_ids.append(attachment_obj.create(cr, uid, data_attach))
+ values['attachment_ids'] = att_ids
+ else:
+ # restore defaults
+ values = self.default_get(cr, uid, self.fields_get_keys(cr, uid), context)
+ values.update(use_template=use_template, template_id=template_id)
+
+ return {'value': values}
+
+
+ def template_toggle(self, cr, uid, ids, context=None):
+ for record in self.browse(cr, uid, ids, context=context):
+ had_template = record.use_template
+ record.write({'use_template': not(record.use_template)})
+ if had_template:
+ # equivalent to choosing an empty template
+ onchange_defaults = self.on_change_template(cr, uid, record.id, record.use_template,
+ False, email_from=record.email_from,
+ email_to=record.email_to, context=context)
+ record.write(onchange_defaults['value'])
+ return _reopen(self, record.id, record.model)
+
+ def save_as_template(self, cr, uid, ids, context=None):
+ if context is None:
+ context = {}
+ email_template = self.pool.get('email.template')
+ model_pool = self.pool.get('ir.model')
+ for record in self.browse(cr, uid, ids, context=context):
+ model = record.model or context.get('active_model')
+ model_ids = model_pool.search(cr, uid, [('model', '=', model)])
+ model_id = model_ids and model_ids[0] or False
+ model_name = ''
+ if model_id:
+ model_name = model_pool.browse(cr, uid, model_id, context=context).name
+ template_name = "%s: %s" % (model_name, tools.ustr(record.subject))
+ values = {
+ 'name': template_name,
+ 'email_from': record.email_from or False,
+ 'subject': record.subject or False,
+ 'body_text': record.body_text or False,
+ 'email_to': record.email_to or False,
+ 'email_cc': record.email_cc or False,
+ 'email_bcc': record.email_bcc or False,
+ 'reply_to': record.reply_to or False,
+ 'model_id': model_id or False,
+ 'attachment_ids': [(6, 0, [att.id for att in record.attachment_ids])]
+ }
+ template_id = email_template.create(cr, uid, values, context=context)
+ record.write({'template_id': template_id,
+ 'use_template': True})
+
+ # _reopen same wizard screen with new template preselected
+ return _reopen(self, record.id, model)
+
+ # override the basic implementation
+ def render_template(self, cr, uid, template, model, res_id, context=None):
+ return self.pool.get('email.template').render_template(cr, uid, template, model, res_id, context=context)
+
+# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: