Электронная почта Excel приходит в другом формате, не в состоянии открыть панд Python - PullRequest
0 голосов
/ 11 июня 2019

Цель - отправить электронное письмо с приложением Excel.Я нашел пример в Интернете, но не для формата Excel.Он отправляет вложение, но не как обычную таблицу Excel, поэтому я не могу его открыть.

Что-то, что я могу изменить в коде для получения файла .xlsx?

enter image description here

# libraries to be imported 
import smtplib 
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 
from email.mime.base import MIMEBase 
from email import encoders 

fromaddr = "From@gmail.com"
toaddr = "To@gmail.com"

# instance of MIMEMultipart 
msg = MIMEMultipart() 

# storing the senders email address   
msg['From'] = fromaddr 

# storing the receivers email address  
msg['To'] = toaddr 

# storing the subject  
msg['Subject'] = "Sending Attachement"

# string to store the body of the mail 
body = "Hello, This is Oleg and my attached file"

# attach the body with the msg instance 
msg.attach(MIMEText(body, 'plain')) 

# open the file to be sent  
filename = "FileName"
attachment = open("C:\\Mylocation\\FileName.xlsx", "rb") 

# instance of MIMEBase and named as p 
p = MIMEBase('application', 'octet-stream') 

# To change the payload into encoded form 
p.set_payload((attachment).read()) 

# encode into base64 
encoders.encode_base64(p) 

p.add_header('Content-Disposition', "attachment; filename= %s" % filename) 

# attach the instance 'p' to instance 'msg' 
msg.attach(p) 

# creates SMTP session 
s = smtplib.SMTP('smtp.gmail.com', 587) 

# start TLS for security 
s.starttls() 

# Authentication 
s.login(fromaddr, "password") 

# Converts the Multipart msg into a string 
text = msg.as_string() 

# sending the mail 
s.sendmail(fromaddr, toaddr, text) 

# terminating the session 
s.quit() 

1 Ответ

1 голос
/ 11 июня 2019

В вашем коде только небольшая ошибка! измените переменную filename на "FileName.xlsx" вместо "FileName"

Я заметил, что у вашего файла нет расширения, и поскольку ваша переменная filename не имеет расширения - вот как я быстро пришел к такому выводу. Документация для add_header(), похоже, также использует расширения файлов.

...