python生成excel并通过邮件发送
时间: 2023-10-18 13:07:00 浏览: 108
以下是生成Excel并通过邮件发送的Python代码,需要使用openpyxl和smtplib库:
```python
import openpyxl
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 创建Excel文件并写入数据
wb = openpyxl.Workbook()
ws = wb.active
ws['A1'] = '姓名'
ws['B1'] = '年龄'
ws['C1'] = '性别'
ws['A2'] = '张三'
ws['B2'] = 20
ws['C2'] = '男'
ws['A3'] = '李四'
ws['B3'] = 25
ws['C3'] = '女'
wb.save('example.xlsx')
# 发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_user = 'your_email@example.com'
smtp_password = 'your_password'
msg = MIMEMultipart()
msg['From'] = smtp_user
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'Python发送Excel邮件'
body = MIMEText('这是一封Python发送的Excel文件邮件。')
msg.attach(body)
with open('example.xlsx', 'rb') as f:
attach = MIMEApplication(f.read(), _subtype='xlsx')
attach.add_header('Content-Disposition', 'attachment', filename='example.xlsx')
msg.attach(attach)
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_user, smtp_password)
server.sendmail(smtp_user, 'recipient@example.com', msg.as_string())
server.quit()
```
需要将代码中的smtp_server、smtp_port、smtp_user和smtp_password替换为实际的值,同时将收件人的邮箱地址替换为实际的地址。运行代码后,将会在当前目录下生成名为example.xlsx的Excel文件,并通过邮件发送给收件人。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)