Skip to Content
Menu
This question has been flagged
1 Reply
5078 Views
@api.multi
def send_mail(self):
email_user = 'laoquocthai1998@gmail.com'
email_send = 'nghieplv@eplatform.vn'
message = "ABCD"
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = "Python"
msg.attach(MIMEText(message, 'plain'))
Obj = self.env['ir.attachment'].search([('res_name', '=', self.name)])
print(Obj[0].name)
file = open(Obj[0].name, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= " + Obj[0].name)
msg.attach(part)

text = msg.as_string()

server = smtplib.SMTP(host='smtp.gmail.com', port=587)
server.starttls()
server.login(email_user, "*********")
server.sendmail(email_user, email_send, text)
server.quit()

I want to upload file to ir_attachment and then get this file will be send to an email, but when i press button send mail, it show error FileNotFoundError: [Errno 2] No such file or directory: Anyone help me ? :(
Avatar
Discard
Best Answer

In Odoo to upload and send a mail, this is the format. as an example

Obj = self.env['ir.attachment'].search([('res_name', '=', self.name)])

values = {
'body': _('<p>Attached files : </p>'),
'model': model.model,
'message_type': 'comment',
'no_auto_thread': False,
'res_id': id_record,
'attachment_ids': [(6, 0, obj and obj.ids)],
}
mail_id = request.env['mail.message'].sudo().create(values)

If you have already some set of file streams then do the following code to add attachments.

for file_name, file_content in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( file_content )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% file_name)
msg.attach(part)

If you are open a file directly then:

for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)

Above two examples are the codes from original send_mail() function. So if you know the attachment ids use the first one. :)


Avatar
Discard
Related Posts Replies Views Activity
9
Jun 23
11124
2
Jan 22
2729
2
Dec 21
6265
0
Jun 21
1005
0
Feb 21
1538