将DataFrame作为邮件正文HTML发送 in Python

  • Overview

    To convert this question into english, maybe:

    How to convert a DataFrame into a petty HTML table and send it over Email, like this one here.

    From R1,there is a module named pretty_html_table .

  • pretty_html_table

    The objective of this package is to convert a pandas dataframe into a pretty html table.

    As of now, 10 colors are available.

  • 其他方案

    通过df.to_html(), 参见R3

  • 延展问题:同时发送HTML和Plain格式的Email

    R2提到,可以同时发送HTML和Plain,通过msg=MIMEMultipart('alternative')实现。

    使用此模块添加html tabl

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() ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值