python 如何将表格当作正文发送邮件
时间: 2024-02-01 08:15:33 浏览: 27
你可以使用Python中的email和smtplib库来发送带有表格的邮件。下面是一个示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import pandas as pd
# 读取表格数据
df = pd.read_excel('table.xlsx')
# 将表格转换为HTML格式
html = df.to_html()
# 创建带有附件的消息对象
msg = MIMEMultipart()
msg['Subject'] = '带有表格的邮件'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
# 将HTML内容添加到消息正文中
body = MIMEText(html, 'html')
msg.attach(body)
# 将表格作为附件添加到消息中
filename = 'table.xlsx'
with open(filename, 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='xlsx')
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)
# 发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'sender@example.com'
smtp_password = 'password'
with smtplib.SMTP(smtp_server, smtp_port) as smtp:
smtp.starttls()
smtp.login(smtp_username, smtp_password)
smtp.send_message(msg)
```
在上面的代码中,我们首先使用pandas库将表格读入到DataFrame对象中,然后使用to_html()方法将其转换为HTML格式。接下来,我们创建了一个带有附件的消息对象,并将HTML内容添加到消息正文中。最后,我们将表格作为附件添加到消息中,并使用smtplib库发送邮件。
请注意,上述代码中的SMTP服务器、端口、用户名和密码需要根据你的实际情况进行更改。