Like other views in Odoo, email template can also be defined in view’s XML file.
Create email template
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="1">
<!--Email template -->
<record id="my_email_template" model="mail.template">
<field name="name">First Email Template</field>
<field name="email_from">${object.name and object.company_id.email or ''}</field>
<field name="subject">New Sale from ${object.company_id.name}</field>
<field name="model_id" ref="my_module.model_custom_model"/>
<field name="auto_delete" eval="True"/>
<field name="lang">${object.address_home_id.lang}</field>
<field name="body_html"><![CDATA[
Dear ${(object.name)}, <br/><br/>
There are 1 sale order.
</div>
]]></field>
</record>
</data>
</odoo>
- name : Template’s name.
- email_from : From email.
- subject : Email’s subject.
- model_id : Determine the module this template belongs to.
- auto_delete : Odoo deletes emails automatically after sending them if the value is True. Otherwise, Odoo keeps created emails.
- lang : Language of the email.
- body_html : Email’s body can contain html tag and inline css.
As you see in the template, we use a lot of ${object}. It is an object of the model we are using in the email template. In our case, it is custom_model in my_module module.
Send email in code
We can override email tempalte’s data before sending like this.
class MyModel(models.Model):
_name = 'my.model'
_description = 'My Model'
@api.multi
def send_email(self):
body_html = 'Hi {},<br/><br/>'.format(someone_name)
body_html += '<ul>'
email_values = {
'email_to': '[email protected]',
'email_from': '[email protected]',
'body_html': body_html,
}
template_id = self.env['mail.template'].search([('model', '=', 'custom.model')], limit=1)
template_id.send_mail(template_id.id, force_send=True, email_values=email_values)