Excel 电子邮件格式不同,无法打开 Python pandas

Excel email comes in a different format unable to open Python pandas

目标是发送带有 excel 附件的电子邮件。 我在网上找到了一个示例,但不是为 Excel 格式编写的。 它发送附件但不像典型的 excel 电子表格,所以我无法打开它。

是否可以在代码中修改以接收 .xlsx 文件?

# 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() 

您的代码中只有一个小错误!将 filename 变量更改为 "FileName.xlsx" 而不仅仅是 "FileName"

我注意到您的文件没有扩展名,而且由于您的 filename 变量没有扩展名 - 这就是我很快得出这个结论的原因。 documentation for add_header() 似乎也使用文件扩展名。