Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • eLearning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Información
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y taberna
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y asistencia informática
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Browse all Industries
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Services for Partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

Send a mail with automatic attachment ofa binary field from a model

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
wizardmailattachmenttemplatebinary
1 Responder
7738 Vistas
Avatar
julien rey

Hi,

I have a model 'quitus.quitus' that contains a binary field 'scanned' as you can see below :

class quitus(osv.Model):
_name='quitus.quitus'
_columns={
    'order_id':fields.many2one('sale.order','Order',required=True),
    'employee_id':fields.many2one('hr.employee','Employee'),
    'description':fields.text('Description',required=True),
    'state':fields.selection([('draft','Draft'),('issued','Issued'),('confirmed','Confirmed')],'State',required=True,readonly=True), 
    'approver':fields.char('Approver',size=100,required=True),
    'scanned':fields.many2one('ir.attachment','Scanned Quitus'),
}
_defaults={
    'state':'draft',
}
def action_confirmed(self, cr, uid, ids):
    for o in self.browse(cr, uid, ids):
        if not o.employee_id:
            raise osv.except_osv(_('Error!'),_('You cannot confirm a quitus without employee'))
        if not o.scanned:
            raise osv.except_osv(_('Error!'),_('You cannot confirm a quitus without scanned doc'))  
    self.write(cr, uid, ids, { 'state' : 'confirmed' })
    return True
def action_issued(self, cr, uid, ids):
    self.write(cr, uid, ids, { 'state' : 'issued' })
    return True
def action_draft(self, cr, uid, ids):
    self.write(cr, uid, ids, { 'state' : 'draft' })
    return True
def action_send_mail(self, cr, uid, ids, context=None):
    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, 'quitus', 'email_quitus_template')[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': 'quitus.quitus',
        '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,

quitus()}

Then on my form view, I have added a button to send a mail :

<record model="ir.ui.view" id="view_quitus_form">
        <field name="name">view.quitus.form</field> 
        <field name="model">quitus.quitus</field> 
        <!-- types: tree,form,calendar,search,graph,gantt,kanban --> 
        <field name="type">form</field> 
        <field name="priority" eval="16"/> 
        <field name="arch" type="xml"> 
            <form string="Quitus form" version="7.0"> 
                    <header>
                        <button name="button_issued" string="Ready for Sign-off" states="draft" type="workflow"/>
                        <button name="button_confirmed" string="Confirm signed-off" states="issued" type="workflow"/>
                        <button name="action_send_mail" string="Send" states="confirmed" type="object"/>
                        <field name="state" 
                                widget="statusbar" 
                                statusbar_visible="draft,issued,confirmed" 
                                statusbar_colors="{"issued":"blue"}"/>
                    </header>
                    <sheet>
                        <h1>Quitus</h1>
                        <group> 
                            <field name="order_id" /> 
                            <field name="approver"/> 
                            <field name="description" /> 
                            <field name="employee_id"/>
                            <field name="scanned" />   
                        </group> 
                    </sheet>                        
            </form> 
        </field> 
    </record>

This button 'action_send_mail' works fine, and use the mail template below

<record id="email_quitus_template" model="email.template">
        <field name="model_id"  ref="quitus.model_quitus_quitus"></field>
        <field name="name">Send Quitus by mail</field>

        <field name="email_from"><![CDATA[${object.order_id.user_id.name} <${object.order_id.user_id.email}>]]></field>
        <field name="email_to"></field>
        <field name="subject">Copie de votre quitus</field>
        <field name="body_html">
            <![CDATA[
                <p>
                    Hello,
                </p>
                <p>
                    You'll find enclosed a copy of your quitus regarding order ${object.order_id.name} / ${object.order_id.client_order_ref}.
                </p>
                <p>
                    This quitus concerns :
                </p>
                <p>
                    ${object.description}
                </p>
                <p>
                    Best regards,
                </p>
                <div style="width: 375px; margin: 0px; padding: 0px; background-color: #8E0000; border-top-left-radius: 5px 5px; border-top-right-radius: 5px 5px; background-repeat: repeat no-repeat;">
                        <h3 style="margin: 0px; padding: 2px 14px; font-size: 12px; color: #DDD;">
                            <strong style="text-transform:uppercase;">${object.order_id.company_id.name}</strong></h3>
                </div>
                <div style="width: 347px; margin: 0px; padding: 5px 14px; line-height: 16px; background-color: #F2F2F2;">
                        <span style="color: #222; margin-bottom: 5px; display: block; ">
                        % if object.order_id.company_id.street:
                            ${object.order_id.company_id.street}<br/>
                        % endif
                        % if object.order_id.company_id.street2:
                            ${object.order_id.company_id.street2}<br/>
                        % endif
                        % if object.order_id.company_id.city or object.order_id.company_id.zip:
                            ${object.order_id.company_id.zip} ${object.order_id.company_id.city}<br/>
                        % endif
                        % if object.order_id.company_id.country_id:
                            ${object.order_id.company_id.state_id and ('%s, ' % object.order_id.company_id.state_id.name) or ''} ${object.order_id.company_id.country_id.name or ''}<br/>
                        % endif
                        </span>
                        % if object.order_id.company_id.phone:
                            <div style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; ">
                                Tél:  ${object.order_id.company_id.phone}
                            </div>
                        % endif
                        % if object.order_id.company_id.website:
                            <div>
                                Web : <a href="${object.order_id.company_id.website}">${object.order_id.company_id.website}</a>
                            </div>
                        %endif
                        <p></p>
                    </div>
                </div>
            ]]>
        </field>
        <field name="attachment_ids">
            ${object.scanned}
        </field>
    </record>

However, I'd like to attach automatically the contents of the binary field 'scanned' to my mail ..I try this way below unsuccesfully

<field name="attachment_ids">
            ${object.scanned}
        </field>

I need some help, i'm little bit confused.

cheers

Julien

0
Avatar
Descartar
Avatar
julien rey
Autor Mejor respuesta

Hi again,

I have finnaly found an acceptable solution. I share my experience for everybody.

I have updated my function send_mail in my quitus object.

def action_send_mail(self, cr, uid, ids, context=None):
    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')
    o = self.browse(cr, uid, ids)[0]
    try:
        #get the template_id
        template_id = ir_model_data.get_object_reference(cr, uid, 'quitus', 'email_quitus_template')[1]
        email_obj = self.pool.get('email.template')  
        #get the object corresponding to template_id
        email = email_obj.browse(cr, uid, template_id)
        #get the id of the document, stored into field scanned
        attachment_id = o.scanned.id
        #write the new attachment to mail template
        email_obj.write(cr, uid, template_id, {'attachment_ids': [(6, 0, [attachment_id ])]})  
    except ValueError:
        template_id = False .......

I change the email.template object before sending mail. I added an attachement from document (ir_attachement).

I hope this could help anyone

Cheers

Julien

1
Avatar
Descartar
sengottuvel

Hi, I have a requirement while confirm a sale order system should send the sale order copy to customer automaticlly with out any user input. Now if you click send mail button again user need to click send button. I created templete and format. How to get atttchment id for send the sale order copy. Kindly help me for complete this requirement. Thanks in advance.

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
Binary field as attachment in mail Resuelto
mail invoice attachment binary
Avatar
Avatar
Avatar
Avatar
Avatar
5
ene 23
17922
Send a mail with fields.binary attached
mail attachment send binary
Avatar
Avatar
4
jun 17
11157
Set default mail template in mail compose/quotations Resuelto
wizard mail template compose quotations
Avatar
Avatar
1
may 18
7356
send email with multiple attachment
mail attachment
Avatar
1
ago 24
2706
Force sender email for all platform mails Resuelto
mail template
Avatar
Avatar
Avatar
Avatar
Avatar
8
jul 24
24867
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now