当前位置: 代码网 > it编程>前端脚本>Python > 使用Python实现自动化办公的代码示例(邮件、excel)

使用Python实现自动化办公的代码示例(邮件、excel)

2025年01月15日 Python 我要评论
一、python 自动化办公的准备工作1.1 安装必要的库在实现自动化办公之前,需要安装相关库。以下是常用的 python 库:邮件自动化:smtplib(发送邮件),imaplib(接收邮件),em

一、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 发送的测试邮件。'
)

注意事项

  1. gmail 用户需开启 “允许不安全应用访问” 或生成 app 密码。
  2. 替换 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自动化办公内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com