python 如何将dataframe当作正文发送邮件
时间: 2024-02-03 13:12:43 浏览: 104
Python中可以使用smtplib和email模块来发送邮件。具体步骤如下:
1. 导入相关模块
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
```
2. 读取DataFrame数据
```python
import pandas as pd
# 读取CSV文件
df = pd.read_csv('data.csv')
```
3. 将DataFrame转换为HTML格式
```python
html_table = df.to_html(index=False)
```
4. 创建MIMEText邮件正文对象
```python
msg = MIMEText(html_table, 'html')
```
5. 创建MIMEMultipart邮件对象
```python
email_from = '发送邮件的邮箱地址'
email_to = '接收邮件的邮箱地址'
msg_root = MIMEMultipart()
msg_root.attach(msg)
msg_root['From'] = email_from
msg_root['To'] = email_to
msg_root['Subject'] = '邮件主题'
```
6. 连接邮件服务器并发送邮件
```python
smtp_server = 'smtp服务器地址'
smtp_port = 'smtp服务器端口号'
smtp_user = '用户名'
smtp_password = '密码'
smtp = smtplib.SMTP(smtp_server, smtp_port)
smtp.login(smtp_user, smtp_password)
smtp.sendmail(email_from, email_to, msg_root.as_string())
smtp.quit()
```
完整代码如下:
```python
import pandas as pd
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 读取CSV文件
df = pd.read_csv('data.csv')
# 将DataFrame转换为HTML格式
html_table = df.to_html(index=False)
# 创建MIMEText邮件正文对象
msg = MIMEText(html_table, 'html')
# 创建MIMEMultipart邮件对象
email_from = '发送邮件的邮箱地址'
email_to = '接收邮件的邮箱地址'
msg_root = MIMEMultipart()
msg_root.attach(msg)
msg_root['From'] = email_from
msg_root['To'] = email_to
msg_root['Subject'] = '邮件主题'
# 连接邮件服务器并发送邮件
smtp_server = 'smtp服务器地址'
smtp_port = 'smtp服务器端口号'
smtp_user = '用户名'
smtp_password = '密码'
smtp = smtplib.SMTP(smtp_server, smtp_port)
smtp.login(smtp_user, smtp_password)
smtp.sendmail(email_from, email_to, msg_root.as_string())
smtp.quit()
```
阅读全文