使用Python实现自动化办公的代码示例(邮件、excel)
作者:王子良.
随着技术的进步,Python 的高效性和易用性使其成为办公自动化的强大工具,通过 Python,我们可以自动处理日常工作中的邮件、Excel 表格等任务,从而大幅提升效率,本文将详细介绍如何使用 Python 实现这些自动化功能,并附上关键代码示例,需要的朋友可以参考下
一、Python 自动化办公的准备工作
1.1 安装必要的库
在实现自动化办公之前,需要安装相关库。以下是常用的 Python 库:
- 邮件自动化:
smtplib
(发送邮件),imaplib
(接收邮件),email
(处理邮件内容)。 - Excel 操作:
openpyxl
(操作 Excel 文件),pandas
(数据处理)。 - 环境配置:
dotenv
(管理环境变量)。
安装方式如下:
pip install openpyxl pandas python-dotenv
1.2 设置邮件服务
为了能够发送和接收邮件,需要:
- 确保邮箱已开启 SMTP(发送)和 IMAP(接收)服务。
- 使用支持授权的 App 密钥(如 Gmail 的“应用专用密码”)。
二、邮件自动化处理
2.1 发送邮件
示例代码
以下代码实现了通过 SMTP 发送邮件:
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def send_email(sender_email, sender_password, recipient_email, subject, body): # 创建邮件对象 msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = recipient_email msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) # 连接到 SMTP 服务器并发送邮件 try: with smtplib.SMTP('smtp.gmail.com', 587) as server: server.starttls() server.login(sender_email, sender_password) server.send_message(msg) print("邮件发送成功!") except Exception as e: print(f"邮件发送失败:{e}") # 调用示例 send_email( sender_email='your_email@gmail.com', sender_password='your_app_password', recipient_email='recipient@example.com', subject='测试邮件', body='这是一封通过 Python 发送的测试邮件。' )
注意事项
- Gmail 用户需开启 “允许不安全应用访问” 或生成 App 密码。
- 替换 SMTP 服务地址时,其他邮箱服务商可能需要不同配置:
- QQ 邮箱:smtp.qq.com
- Outlook:smtp.office365.com
2.2 接收和读取邮件
示例代码
以下代码展示如何通过 IMAP 读取未读邮件:
import imaplib import email def fetch_emails(email_address, password): try: # 连接 IMAP 服务器 with imaplib.IMAP4_SSL('imap.gmail.com') as mail: mail.login(email_address, password) mail.select('inbox') # 选择收件箱 # 搜索未读邮件 status, messages = mail.search(None, 'UNSEEN') for num in messages[0].split(): status, msg_data = mail.fetch(num, '(RFC822)') for response_part in msg_data: if isinstance(response_part, tuple): msg = email.message_from_bytes(response_part[1]) print(f"发件人: {msg['from']}") print(f"主题: {msg['subject']}") if msg.is_multipart(): for part in msg.walk(): if part.get_content_type() == 'text/plain': print(f"内容: {part.get_payload(decode=True).decode()}") else: print(f"内容: {msg.get_payload(decode=True).decode()}") except Exception as e: print(f"邮件读取失败:{e}") # 调用示例 fetch_emails('your_email@gmail.com', 'your_app_password')
三、Excel 自动化处理
3.1 读取和写入 Excel 文件
示例代码
使用 openpyxl
读取和写入 Excel:
import openpyxl # 打开 Excel 文件 workbook = openpyxl.load_workbook('example.xlsx') sheet = workbook.active # 读取数据 for row in sheet.iter_rows(min_row=1, max_row=5, min_col=1, max_col=3): print([cell.value for cell in row]) # 写入数据 sheet['A6'] = '新数据' workbook.save('example_updated.xlsx') print("Excel 文件已更新!")
3.2 数据处理和分析
示例代码
使用 pandas
对 Excel 数据进行分析:
import pandas as pd # 读取 Excel 文件 data = pd.read_excel('example.xlsx') # 打印前五行数据 print(data.head()) # 数据处理 data['总分'] = data['数学'] + data['英语'] + data['科学'] print(data) # 保存结果 data.to_excel('processed.xlsx', index=False) print("数据处理完成并已保存!")
四、综合实例:从邮件中读取 Excel 附件并分析
以下代码展示了一个完整的自动化工作流:
- 接收邮件并提取附件。
- 读取 Excel 数据,进行分析。
- 将结果发送回发件人。
示例代码
import os import imaplib import email import pandas as pd from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import smtplib def fetch_and_process_email(email_address, password): # 连接 IMAP with imaplib.IMAP4_SSL('imap.gmail.com') as mail: mail.login(email_address, password) mail.select('inbox') # 搜索含附件邮件 status, messages = mail.search(None, 'ALL') for num in messages[0].split(): status, msg_data = mail.fetch(num, '(RFC822)') for response_part in msg_data: if isinstance(response_part, tuple): msg = email.message_from_bytes(response_part[1]) if msg.is_multipart(): for part in msg.walk(): if part.get_filename(): # 找到附件 file_path = os.path.join(os.getcwd(), part.get_filename()) with open(file_path, 'wb') as f: f.write(part.get_payload(decode=True)) print(f"附件已保存: {file_path}") # 处理附件数据 data = pd.read_excel(file_path) data['总分'] = data.sum(axis=1) processed_path = 'processed.xlsx' data.to_excel(processed_path, index=False) print("数据处理完成") # 返回处理结果 send_email( sender_email=email_address, sender_password=password, recipient_email=msg['from'], subject='数据处理结果', body='附件已处理,请查看。', attachment_path=processed_path ) def send_email(sender_email, sender_password, recipient_email, subject, body, attachment_path): msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = recipient_email msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) # 添加附件 with open(attachment_path, 'rb') as f: attachment = email.mime.base.MIMEBase('application', 'octet-stream') attachment.set_payload(f.read()) email.encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', f'attachment; filename={os.path.basename(attachment_path)}') msg.attach(attachment) # 发送邮件 with smtplib.SMTP('smtp.gmail.com', 587) as server: server.starttls() server.login(sender_email, sender_password) server.send_message(msg) print("邮件已发送!") # 调用示例 fetch_and_process_email('your_email@gmail.com', 'your_app_password')
到此这篇关于使用Python实现自动化办公的代码示例(邮件、excel)的文章就介绍到这了,更多相关Python自动化办公内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!