python中使用MIMEText发送xlsx文件
时间: 2024-02-24 19:57:28 浏览: 121
用Python将结果保存为xlsx的方法
5星 · 资源好评率100%
可以使用Python中的smtplib和email库来发送带有xlsx附件的邮件。下面是一个简单的示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 邮件服务器地址、用户名、密码
smtp_server = 'smtp.xxx.com'
username = 'your_username'
password = 'your_password'
# 发件人、收件人、邮件主题
sender = 'xxx@xxx.com'
receiver = 'yyy@yyy.com'
subject = 'Test Email'
# 构造邮件对象
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
# 添加邮件正文
body = 'This is a test email.'
text = MIMEText(body)
msg.attach(text)
# 添加附件
with open('sample.xlsx', 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='xlsx')
attachment.add_header('content-disposition', 'attachment', filename='sample.xlsx')
msg.attach(attachment)
# 发送邮件
try:
smtp = smtplib.SMTP(smtp_server)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
print('Email sent successfully.')
except Exception as e:
print('Email sent failed.')
print(e)
finally:
smtp.quit()
```
需要注意的是,邮件正文和附件都需要使用MIME格式来构造。在添加附件时,需要先读取文件内容,然后将其作为MIMEApplication对象添加到邮件中。同时,还需要设置附件的content-disposition头部信息,以指定附件的文件名。
阅读全文