python自动生成Excel表格数据并发送邮件案例

简介: python自动生成Excel表格数据并发送邮件案例

要使用Python自动生成Excel表格数据并发送邮件,您可以使用pandas库来处理数据,使用openpyxl库来生成Excel表格,并使用smtplib和email.mime库来发送邮件。下面是一个简单的示例代码:

python
import pandas as pd
from openpyxl import Workbook
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

生成数据

data = {
'Product': ['Apple', 'Banana', 'Orange'],
'Price': [1.00, 0.50, 0.75],
'Quantity': [50, 20, 30]
}
df = pd.DataFrame(data)

生成Excel表格

wb = Workbook()
ws = wb.active
for r in dataframe_to_rows(df, index=False, header=True):
ws.append(r)
wb.save('example.xlsx')

发送邮件

sender = 'your_email@example.com'
password = 'your_password'
recipient = 'recipient@example.com'
subject = 'Excel表格数据'
body = '以下是生成的Excel表格数据:'
attachment = 'example.xlsx'

msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = recipient
msg['Subject'] = subject

msg.attach(MIMEText(body, 'plain'))
with open(attachment, 'rb') as f:
msg.attach(MIMEText(f.read(), 'base64', 'unix'))

smtp = SMTP('smtp.gmail.com:587')
smtp.starttls()
smtp.login(sender, password)
smtp.sendmail(sender, recipient, msg.as_string())
smtp.quit()
在上面的代码中,我们首先使用pandas库生成了一个包含产品、价格和数量的数据字典,然后将其转换为数据框。接下来,我们使用openpyxl库将数据框转换为Excel表格,并将其保存到本地文件example.xlsx中。然后,我们使用smtplib和email.mime库来发送邮件。在邮件正文中,我们简单地描述了附件的内容。在附件中,我们附加了生成的Excel表格文件。最后,我们使用Gmail的SMTP服务器发送邮件。请确保在运行代码之前替换发件人和密码以及收件人邮箱。

相关文章
|
5天前
|
Python
python_读写excel、csv记录
python_读写excel、csv记录
10 0
|
5天前
|
JavaScript 前端开发 BI
原生html—摆脱ps、excel 在线绘制财务表格加水印(html绘制表格js加水印)
原生html—摆脱ps、excel 在线绘制财务表格加水印(html绘制表格js加水印)
9 1
|
12天前
|
小程序 数据挖掘 iOS开发
Python + Excel 办公自动化 01 —— 硬菜马上就来
Python + Excel 办公自动化 01 —— 硬菜马上就来
21 1
|
12天前
|
存储 Python
终于,手把手教会 HR 实现 Python + Excel 「邮件自动化」发工资条了
终于,手把手教会 HR 实现 Python + Excel 「邮件自动化」发工资条了
18 0
|
12天前
|
数据挖掘 索引 Python
Python 读写 Excel 文件
Python 读写 Excel 文件
12 0
|
18天前
|
Python
Python—提取页面上所有信息输出excel
Python—提取页面上所有信息输出excel
|
3月前
|
数据采集 JSON JavaScript
Python爬虫案例:抓取猫眼电影排行榜
python爬取猫眼电影排行榜数据分析,实战。(正则表达式,xpath,beautifulsoup)【2月更文挑战第11天】
71 2
Python爬虫案例:抓取猫眼电影排行榜
|
3月前
|
Web App开发 数据采集 前端开发
Python Selenium 爬虫淘宝案例
本文基于Selenium + MongoDB + ChromeDriver + Pyquery实现爬虫淘宝案例。【2月更文挑战第11天】
103 1
Python Selenium 爬虫淘宝案例
|
4月前
|
数据采集 Python
简单的Python爬虫案例
这个简单的爬虫案例将访问目标网站,获取其HTML内容,然后解析HTML并提取所有的标题。
44 5
|
10月前
|
数据采集 存储 Web App开发
Python爬虫技术的应用案例:聚焦热点话题与趋势分析
Python爬虫技术的应用案例:聚焦热点话题与趋势分析