Odoo Help

Welcome!

This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.

3

Send eMail template through code

By
Atchuthan
on 6/18/13, 10:59 AM 20,618 views
Hi friendz,

          When sending the mail by clicking button "send by Email" in "addition" module,  the following error comes:
          AttributeError: 'addition' object has no attribute 'message_post'

__openerp__.py:

{
    "name": "addition",
    "version": "7.0",
    "summary" : "addition of 2 nos",
    "depends": ["base","mail","email_template"],
    "author": "atchuthan",
    "category": "Others",
    "description": """
    This module provide : summation of 2 integer numbers  
    """,
     'data' : ['addition_view.xml','addition_action_data.xml'],
    'demo_xml': [],
    'installable': True,
    'auto-install' : True,
    'active': False
}

addition.py:

from osv import osv, fields
from openerp.tools.translate import _

class addition(osv.osv):
    _name = 'addition' 
    _rec_name = 'result'  
    _columns = {
            'number1': fields.integer('number 1', required=True),
            'number2' : fields.integer('number 2', required=True),
            'result' : fields.integer('Result'),
                    }

    def action_addition_send(self, cr, uid, ids, context=None):
            '''
            This function opens a window to compose an email, with the edi sale template message loaded by default
            '''
            assert len(ids) == 1, 'This option should only be used for a single id at a time.'
            ir_model_data = self.pool.get('ir.model.data')
            try:
                template_id = ir_model_data.get_object_reference(cr, uid, 'addition', 'email_template_edi_addition')[1]
            except ValueError:
                template_id = False
            try:
                compose_form_id = ir_model_data.get_object_reference(cr, uid, 'mail', 'email_compose_message_wizard_form')[1]
            except ValueError:
                compose_form_id = False 
            ctx = dict(context)
            ctx.update({
                'default_model': 'addition',
                'default_res_id': ids[0],
                'default_use_template': bool(template_id),
                'default_template_id': template_id,
                'default_composition_mode': 'comment',
                'mark_so_as_sent': True
            })
            return {
                'type': 'ir.actions.act_window',
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'mail.compose.message',
                'views': [(compose_form_id, 'form')],
                'view_id': compose_form_id,
                'target': 'new',
                'context': ctx,
            }

class mail_compose_message(osv.Model):
    _inherit = 'mail.compose.message'

    def send_mail(self, cr, uid, ids, context=None):
        context = context or {}
        if context.get('default_model') == 'addition' and context.get('default_res_id') and context.get('mark_so_as_sent'):
            context = dict(context, mail_post_autofollow=True)
        return super(mail_compose_message, self).send_mail(cr, uid, ids, context=context)

addition_view.xml:

<?xml version="1.0" encoding="utf-8" ?>
<openerp>
    <data>
        <record model="ir.ui.view" id="addition_tree_view">
            <field name="name">addition.tree</field>
            <field name="model">addition</field>
            <field name="type">tree</field>
            <field name="arch" type="xml">
                <tree string="addition_tree">
                    <field name="number1" />
                    <field name="number2" />
                    <field name="result" />
                </tree>
            </field>
        </record>
        <record model="ir.ui.view" id="addition_form_view">
            <field name="name">addition.form</field>
            <field name="model">addition</field>
            <field name="type">form</field>
            <field name="arch" type="xml">
                <form string="addition_form" version="7.0">
                    <header>
                        <button name="action_addition_send" string="Send by Email"
                            type="object" class="oe_highlight" />
                    </header>
                    <sheet>
                        <group>
                            <field name="number1" onchange="onchange_addition(number1, number2)" />
                            <field name="number2" onchange="onchange_addition(number1, number2)" />
                            <field name="result" />  <!-- onchange_addition(number1, number2) -->
                        </group>
                    </sheet>
                </form>
            </field>
        </record>
        <record model="ir.actions.act_window" id="action_addition_form">
            <field name="name">addition</field>
            <field name="res_model">addition</field>
        </record>
        <menuitem name="Parent" icon="terp-project" id="parent_id" />
        <menuitem name="Son" parent="parent_id" id="son_id" />
        <menuitem name="Addition" parent="son_id" id="addition_id"
            action="action_addition_form" />
    </data>
</openerp>

addition_action_data.xml:

<?xml version="1.0" ?>
<openerp>
    <data>
        <!-- EDI related Email Templates menu -->
        <record model="ir.actions.act_window" id="action_email_templates">
            <field name="name">Email Templates</field>
            <field name="res_model">email.template</field>
            <field name="view_type">form</field>
            <field name="view_mode">form,tree</field>
            <field name="view_id" ref="email_template.email_template_tree" />
            <field name="search_view_id" ref="email_template.view_email_template_search" />
            <field name="context"
                eval="{'search_default_model_id': ref('model_addition')}" />
        </record>
    </data>

    <!-- Mail template are declared in a NOUPDATE block so users can freely 
        customize/delete them -->
    <data noupdate="1">
        <!--Email template -->
        <record id="email_template_edi_addition" model="email.template">
            <field name="name">Addition 2 nos - Send by mail</field>
            <field name="email_from">bms@openerp.com</field>
            <field name="subject">addition</field>
            <field name="email_to">atchuthantu@yahoo.com</field>
            <field name="auto_delete" eval="True" />
            <field name="model_id" ref="model_addition" />
            <field name="body_html"><![CDATA[
<div style="font-family: 'Lucica Grande', Ubuntu, Arial, Verdana, sans-serif; font-size: 12px; color: rgb(34, 34, 34); background-color: #FFF; ">

    <p>Hello,</p>

    <p>Addition successful</p>

</div>
            ]]></field>
        </record>
    </data>
</openerp>

traceback:

2013-06-18 12:56:43,251 3505 INFO bms werkzeug: 127.0.0.1 - - [18/Jun/2013 12:56:43] "POST /web/dataset/call_kw/mail.compose.message:create HTTP/1.1" 200 -
2013-06-18 12:56:43,314 3505 INFO bms werkzeug: 127.0.0.1 - - [18/Jun/2013 12:56:43] "POST /web/dataset/call_kw/mail.compose.message:read HTTP/1.1" 200 -
2013-06-18 12:56:43,392 3505 INFO bms werkzeug: 127.0.0.1 - - [18/Jun/2013 12:56:43] "POST /web/dataset/call_kw/res.partner:name_get HTTP/1.1" 200 -
2013-06-18 12:56:43,418 3505 ERROR bms openerp.osv.osv: Uncaught exception
Traceback (most recent call last):
  File "/var/app/openerp/server/openerp/osv/osv.py", line 131, in wrapper
    return f(self, dbname, *args, **kwargs)
  File "/var/app/openerp/server/openerp/osv/osv.py", line 197, in execute
    res = self.execute_cr(cr, uid, obj, method, *args, **kw)
  File "/var/app/openerp/server/openerp/osv/osv.py", line 185, in execute_cr
    return getattr(object, method)(cr, uid, *args, **kw)
  File "/var/app/openerp/addons/bms/bms.py", line 304, in send_mail
    return super(mail_compose_message, self).send_mail(cr, uid, ids, context=context)
  File "/var/app/openerp/addons/addition/addition.py", line 55, in send_mail
    return super(mail_compose_message, self).send_mail(cr, uid, ids, context=context)
  File "/var/app/openerp/addons/email_template/wizard/mail_compose_message.py", line 80, in send_mail
    return super(mail_compose_message, self).send_mail(cr, uid, ids, context=context)
  File "/var/app/openerp/addons/mail/wizard/mail_compose_message.py", line 259, in send_mail
    msg_id = active_model_pool.message_post(cr, uid, [res_id], type='comment', subtype=subtype, context=context, **post_values)
AttributeError: 'addition' object has no attribute 'message_post'
2013-06-18 12:56:43,430 3505 ERROR bms openerp.netsvc: 'addition' object has no attribute 'message_post'
Traceback (most recent call last):
  File "/var/app/openerp/server/openerp/netsvc.py", line 293, in dispatch_rpc
    result = ExportService.getService(service_name).dispatch(method, params)
  File "/var/app/openerp/server/openerp/service/web_services.py", line 626, in dispatch
    res = fn(db, uid, *params)
  File "/var/app/openerp/server/openerp/osv/osv.py", line 188, in execute_kw
    return self.execute(db, uid, obj, method, *args, **kw or {})
  File "/var/app/openerp/server/openerp/osv/osv.py", line 131, in wrapper
    return f(self, dbname, *args, **kwargs)
  File "/var/app/openerp/server/openerp/osv/osv.py", line 197, in execute
    res = self.execute_cr(cr, uid, obj, method, *args, **kw)
  File "/var/app/openerp/server/openerp/osv/osv.py", line 185, in execute_cr
    return getattr(object, method)(cr, uid, *args, **kw)
  File "/var/app/openerp/addons/bms/bms.py", line 304, in send_mail
    return super(mail_compose_message, self).send_mail(cr, uid, ids, context=context)
  File "/var/app/openerp/addons/addition/addition.py", line 55, in send_mail
    return super(mail_compose_message, self).send_mail(cr, uid, ids, context=context)
  File "/var/app/openerp/addons/email_template/wizard/mail_compose_message.py", line 80, in send_mail
    return super(mail_compose_message, self).send_mail(cr, uid, ids, context=context)
  File "/var/app/openerp/addons/mail/wizard/mail_compose_message.py", line 259, in send_mail
    msg_id = active_model_pool.message_post(cr, uid, [res_id], type='comment', subtype=subtype, context=context, **post_values)
AttributeError: 'addition' object has no attribute 'message_post'
2013-06-18 12:56:43,432 3505 INFO bms werkzeug: 127.0.0.1 - - [18/Jun/2013 12:56:43] "POST /web/dataset/call_button HTTP/1.1" 200 -
0

Atchuthan - Technical Consultant, Sodexis Inc

--Atchuthan - Technical Consultant, Sodexis Inc--
3883
| 5 3 8
Puducherry, India
--Atchuthan - Technical Consultant, Sodexis Inc--
Passionate coder in Python/Odoo(formerly known as OpenERP).

Contact me via GMail: atchuthantu@gmail.com via Skype: atchuthan_skype
via Linkedin: http://in.linkedin.com/in/atchuthantu
Atchuthan - Technical Consultant, Sodexis Inc
On 8/22/13, 6:04 AM

Try to modify code :

        template_id = ir_model_data.get_object_reference(cr, uid, 'sale', 'email_template_edi_sale')[1]

here sale implies folder name of your module

        'default_model': 'sale.order',

here specify the model name i.e. table name

7

Ghanshyam Prajapati

--Ghanshyam Prajapati--
1377
| 4 4 8
Pune, India
--Ghanshyam Prajapati--
OpenERP Developer
Ghanshyam Prajapati
On 6/19/13, 4:18 AM

Use Following simple method for send email,

def send_mail(self, cr, uid, ids, context=None):
    email_template_obj = self.pool.get('email.template')
    template_ids = email_template_obj.search(cr, uid, [('model_id.model', '=','your.object.name')], context=context) 
    if template_ids:
          values = email_template_obj.generate_email(cr, uid, template_ids[0], ids, context=context)
         values['subject'] = subject 
          values['email_to'] = email_to
          values['body_html'] = body_html
          values['body'] = body_html
          values['res_id'] = False
          mail_mail_obj = self.pool.get('mail.mail')
          msg_id = mail_mail_obj.create(cr, uid, values, context=context)
          if msg_id:
                mail_mail_obj.send(cr, uid, [msg_id], context=context) 
    return True

Hi atchuthan, If your problem is solved please mark the answer as solved.

Ghanshyam Prajapati
on 6/19/13, 7:59 AM

Suppose you have created one template for sending emails, under your template, you can see Applies To(model_id). Now in my answer, you can see 'your.object.name' in template_ids line, Replace 'your.object.name' with your current template's model_id's object name.

Ghanshyam Prajapati
on 6/19/13, 9:06 AM

Hi dude, I am getting error when I tried your suggestion as "IndexError: list index out of range"

Atchuthan
on 6/20/13, 4:08 AM

in server you can see error line number with file name, please check your error location, or debug your code. see http://www.youtube.com/watch?v=RTg8VvyEVak

Ghanshyam Prajapati
on 6/20/13, 4:15 AM

See my updated answer, Try to print template_ids, you can see template_ids=[], it means search method cant find your template. try hardcode, Put your template's id in blank list and then check, for example, template_ids = [1]

Ghanshyam Prajapati
on 6/20/13, 8:53 AM

I got this error when I use above code-----------Odoo 8.0-20141016-000205\server\openerp\addons\email_template\email_template.py", line 219, in get_email_template_batch TypeError: unhashable type: 'list'

Odoo
on 10/24/14, 12:56 AM

I got this error when I use above code-----------Odoo 8.0-20141016-000205\server\openerp\addons\email_template\email_template.py", line 219, in get_email_template_batch TypeError: unhashable type: 'list'

Odoo
on 10/24/14, 1:05 AM

It worked for me... superb.. I upvoted you.. Also help me to create a template using xml or python code....

Anand
on 11/29/14, 5:05 AM
3

Sandeep

--Sandeep--
6083
| 6 5 8
Delhi, India
--Sandeep--
Python OpenERP Developer http://in.linkedin.com/pub/sandeep-rana/3b/a16/786/
Sandeep
On 6/19/13, 3:50 AM

Hi

Try to use send function of email.template , this will be better and easy for you just need to include current record ID and template id and another field of true and false for send immediately or later

that's it

Thanks
Sandeep

can u provide me with appropriate code with send function of email.template for my module "addition".

template_id = "email_template_edi_addition"

Atchuthan
on 6/19/13, 3:55 AM

templateobject.send(cr,uid,template_id,your_record_id,True) this is the simple method

Sandeep
on 6/19/13, 3:58 AM

can u tell me where to add this code and what to write in the body of this method

Atchuthan
on 6/19/13, 4:03 AM

this method is of email.template object , you just need to cal this , call this method from your code

Sandeep
on 6/19/13, 4:05 AM

Can you help writing a simple send email function code that runs on a button, as simple as it can be as. I want to use this code in partner ledger webkit wizard, it should read the selected partner's email and use the report as attachment. Its very urgent.

evon_dun
on 10/9/13, 7:43 AM

Look at account_invoice.py, method action_invoice_sent - this is what happens when you click Send as Email on an invoice.

Torvald Baade Bringsvor, Torvald B. Bringsvor
on 4/25/14, 8:50 AM

Hi could not find such a method!

evon_dun
on 4/25/14, 9:37 AM

Your Answer

Please try to give a substantial answer. If you wanted to comment on the question or answer, just use the commenting tool. Please remember that you can always revise your answers - no need to answer the same question twice. Also, please don't forget to vote - it really helps to select the best questions and answers!

About This Community

This community is for professionals and enthusiasts of our products and services. Read Guidelines

Question tools

2 follower(s)

Stats

Asked: 6/18/13, 10:59 AM
Seen: 20618 times
Last updated: 10/20/16, 2:44 AM