Create Email Template and Send Email Programmatically in Odoo 12

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"?>
    <data noupdate="1">
        <!--Email template -->
        <record id="my_email_template" model="mail.template">
            <field name="name">First Email Template</field>
            <field name="email_from">${ and or ''}</field>
            <field name="subject">New Sale from ${}</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 ${(}, <br/><br/>
   There are 1 sale order.
  • 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'

    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(, force_send=True, email_values=email_values)

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top