Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

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

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

Binary field as attachment in mail

Subscriure's

Get notified when there's activity on this post

This question has been flagged
mailinvoiceattachmentbinary
5 Respostes
17904 Vistes
Avatar
Hugo M.

Hello,

I'm developing a module to extend Invoice (Odoo 11). I have added a binary field into the Invoice model, and I want to be able to send this binary via mail.

Sending an e-mail directly and attaching a binary is simple, but I want to open the composer wizard with the binary as an attachment. Currently, the "Send by e-mail" button opens the composer with Odoo's default PDF report; I want to add another file in that view.

This is my current code to try to attach the files. This piece of code itself runs and doesn't generate any errors, but the composer wizard just ignores the added info.

@api.multi
def action_invoice_sent(self):
self.ensure_one()

result = super(AccountInvoice,self).action_invoice_sent()

pdf_attachment_id = self.env['ir.attachment'].create({
'name': ("%s" %self.pdf),
'datas': self.pdfname,
'datas_fname': self.pdf,
'res_model': 'mail.compose.message',
'res_id': 0,
'type': 'binary'
})

result['context'].update({
'attachment_ids': [(6,0,[pdf_attachment_id.id])]
})

return result

Thanks a lot!
1
Avatar
Descartar
Avatar
Hugo M.
Autor Best Answer

Thanks but that's not my question. I don't want to attach a PDF report, the default invoice's e-mail template already does that. I want to add *another* file in the e-mail

I already solved it by extending the Composer wizard to retrieve the added files in context, but thanks anyway.

0
Avatar
Descartar
Avatar
Megha Patel
Best Answer

Hugo M.

Firstly you have to check that the attachment you are sending is in pdf format or not, if its not then convert it using get_pdf method.

here is the example of attached report,

@api.multi
def action_rfq_send(self):
    self.ensure_one()
    ir_model_data = self.env['ir.model.data']
    try:
        if self.env.context.get('send_rfq', False):
            temp_id = self.env.ref('purchase.email_template_edi_purchase')
        else:
            temp_id = self.env.ref(
                               'purchase.email_template_edi_purchase_done')
    except ValueError:
        temp_id = False
    try:
        compose_form_id = ir_model_data.get_object_reference('mail',
                         'email_compose_message_wizard_form')[1]
    except ValueError:
        compose_form_id = False

    attach_obj = self.env['ir.attachment']

    pdf_rfq_quote = self.env['report'].sudo().get_pdf([self.id],
                                             'report name')
    result_rfq_quote = base64.b64encode(pdf_rfq_quote)

    attachment_ids = []
    if result:
        attach_data = {
            'name': 'name.pdf',
            'datas': result_rfq_quote,
            'datas_fname': 'name.pdf',
            'res_model': 'ir.ui.view',
            }
        attach_id = attach_obj.create(attach_data)
        attachment_ids.append(attach_id.id)
    if attachment_ids:
        temp_id.write({'attachment_ids': [(6, 0, attachment_ids)]})

    ctx = dict(self.env.context or {})
        ctx.update({
            'default_model': 'purchase.order',
            'default_res_id': self.ids[0],
            'default_use_template': bool(temp_id.id),
            'default_template_id': temp_id.id,
            'default_composition_mode': 'comment',
        })
        return {
            'name': _('Compose Email'),
            '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,
        }
       

Thank You

1
Avatar
Descartar
Avatar
Mohamed Amine Kaabi
Best Answer

it works with pdf file ?


0
Avatar
Descartar
Avatar
Gabriel Hernandez
Best Answer
Thanks but that's not my question. I don't want to attach a PDF report, the default invoice's e-mail template already does that. I want to add *another* file in the e-mail
I already solved it by extending the Composer wizard to retrieve the added files in context, but thanks anyway.


I want to do the same, how to solve this?

Thank you.
0
Avatar
Descartar
Avatar
Carlos Alberto García Brizuela
Best Answer

Hello, this is my implementation using odoo email wizard:

def send_mail(self):
self.ensure_one()
template = self.env.ref('my_module.email_template_payroll', False)
compose_form = self.env.ref('mail.email_compose_message_wizard_form', False)

# attach xml from binary field
if self.xml_data:
xml_name = '%s.xml' % self.name
attachment_ids = []
encoded_data = base64.b64encode(self.xml_data)
decoded_data = base64.b64decode(encoded_data)

if decoded_data:
attach_data = {
'name': xml_name,
'res_name': xml_name,
'datas': decoded_data,
'res_model': 'hr.payslip',
'res_id': self.id,
}
attach_id = self.env['ir.attachment'].create(attach_data)
attachment_ids.append(attach_id.id)

if attachment_ids:
template.write({'attachment_ids': [(6, 0, attachment_ids)]})

ctx = dict()
ctx.update({
'default_model': 'hr.payslip',
'default_res_id': self.id,
'default_use_template': bool(template),
'default_template_id': template.id,
'default_composition_mode': 'comment',
})


return {
'name': _('Compose Email'),
'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,
}

Be careful with the indentation of the code, it got lost when paste text.

Hope it helps


0
Avatar
Descartar
Mohamed Amine Kaabi

xml_data a existing field ?

Carlos Alberto García Brizuela

"xml_data" field is a binary stored field in the same model of your method "send_mail". not remember if its a native odoo field or a custom one.

Mohamed Amine Kaabi

it works with pdf file ?

Carlos Alberto García Brizuela

I think should work too, pdf files are stored by odoo in binary fields as well.

Mohamed Amine Kaabi

i have this error

File "/home/ibs/Bureau/workspace/odoo13/odoo/api.py", line 390, in call_kw
result = _call_kw_multi(method, model, args, kwargs)
File "/home/ibs/Bureau/workspace/odoo13/odoo/api.py", line 377, in _call_kw_multi
result = method(recs, *args, **kwargs)
File "/home/ibs/Bureau/workspace/odoo13/test_erp/spc_intranet_sfr/models/hs_commande.py", line 278, in action_commande_send
encoded_data = base64.b64encode(self.attachment_access_adsl)
File "/usr/lib/python3.8/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'ir.attachment'

Mohamed Amine Kaabi

This is the function
def action_commande_send(self):
self.ensure_one()
template = self.env.ref('spc_intranet_sfr.email_template_hs_commande', False)
compose_form = self.env.ref('mail.email_compose_message_wizard_form', False)

if self.attachment_access_adsl:
pdf_name = '%s.pdf' % self.name
attachment_ids = []
encoded_data = base64.b64encode(self.attachment_access_adsl)
decoded_data = base64.b64decode(encoded_data)

if decoded_data:
attach_data = {
'name': pdf_name,
'res_name': pdf_name,
'datas': decoded_data,
'res_model': 'hs.commande',
'res_id': self.id,
}
attach_id = self.env['ir.attachment'].create(attach_data)
attachment_ids.append(attach_id.id)

if attachment_ids:
template.write({'attachment_ids': [(6, 0, attachment_ids)]})

ctx = dict()
ctx.update({
'default_model': 'hs.commande',
'default_res_id': self.id,
'default_use_template': bool(template),
'default_template_id': template.id,
'default_composition_mode': 'comment',
})
return {
'name': _('Compose Email'),
'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,
}

Carlos Alberto García Brizuela

The error is in this line:
encoded_data = base64.b64encode(self.attachment_access_adsl)

I think you are passing the full model or class object, but you need to pass the binary field instead, for example:

encoded_data = base64.b64encode(self.attachment_access_adsl.bin_field_name)

Mohamed Amine Kaabi

bin_field_name ?!!!!!!

Carlos Alberto García Brizuela

base64.b64encode(*)

This method expects binary data as a parameter, you are passing an instance object of the class "ir.attachment".

what you need to pass is the binary field of the class "ir.attachment". In odoo 15 the binary field name is "datas"

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Related Posts Respostes Vistes Activitat
Send a mail with fields.binary attached
mail attachment send binary
Avatar
Avatar
4
de juny 17
11132
send email with multiple attachment
mail attachment
Avatar
1
d’ag. 24
2700
Send a mail with automatic attachment ofa binary field from a model
wizard mail attachment template binary
Avatar
1
de març 15
7723
Attachments in openerp 7.0
invoice attachment
Avatar
Avatar
Avatar
3
de març 15
9792
Send invoice by email: attachments creation
invoice attachment
Avatar
Avatar
1
de març 15
7131
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة 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 és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

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