Sending e-mail with excel attachment - Python

Asked

Viewed 805 times

0

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

email_user = '[email protected]'
email_send = '[email protected]'
subject = 'Python'

msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject


body = "HI"
msg.attach(MIMEText(body, 'plain'))

filename = 'caminho_para_arquivo\\Documentos.xlsx'
attachment = open(filename, 'rb')

part = MIMEBase('application', 'octet-stream')

attachment = base64.b64encode(bytes(attachment, 'utf-8'))

part.set_payload((attachment).read)

encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachament; filename="+filename)

msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_user, 'xxxxxx')


server.sendmail(email_user, email_send, text)
server.quit()

I’m getting the error of:

TypeError: encoding without a string argument

I wonder if it is possible to send spreadsheet or any other extension of excel.

1 answer

1


Hello, it is possible to send any other extension of Excel by email.

Looking at your code I made a small change in the attaching part of the file

part = MIMEBase('application', "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="WorkBook3.xlsx"')
message.attach(part)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.