Python自动化操作Excel与发送邮件代码示例

键盘旁的猫
键盘旁的猫
发布时间:2026-12-03 | 815人浏览过
原创

使用 openpyxl 读写 Excel ,配合 smtplib 和 MIMEText 发送邮件。先安装依赖,再按示例配置邮箱账号与文件路径即可运行。

Python自动化操作Excel与发送邮件代码示例

Excel 数据读取与处理

用 load_workbook 打开工作簿,遍历行获取单元格值,过滤空数据后存入列表。

Python自动化操作Excel与发送邮件代码示例

确保 Excel 文件存在且格式正确,避免 FileNotFoundError。读取时跳过表头,仅处理有效数据行。

邮件发送逻辑实现

通过 SMTP 连接服务器,构建邮件对象并附加 Excel 文件,设置发件人、收件人与主题。

Python自动化操作Excel与发送邮件代码示例

import openpyxl
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os

def read_excel(file_path):
    wb = openpyxl.load_workbook(file_path)
    ws = wb.active
    data = []
    for row in ws.iter_rows(min_row=2, values_only=True):
        if any(cell is not None for cell in row):
            data.append(list(row))
    return data

def send_email(sender, password, receiver, subject, body, file_path):
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    
    with open(file_path, 'rb') as f:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(f.read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', f'attachment; filename="{os.path.basename(file_path)}"')
    msg.attach(part)
    
    server = smtplib.SMTP('smtp.example.com', 587)
    server.starttls()
    server.login(sender, password)
    server.sendmail(sender, receiver, msg.as_string())
    server.quit()

if __name__ == '__main__':
    excel_file = 'data.xlsx'
    if os.path.exists(excel_file):
        data = read_excel(excel_file)
        print(f'Read {len(data)} rows.')
        send_email('sender@example.com', 'auth_code', 'receiver@example.com', 'Report', 'See attached.', excel_file)
        print('Email sent.')
    else:
        print('File not found.')

程序输出读取的行数及发送成功提示。若文件缺失则打印未找到信息。修改邮箱地址与授权码后可实际运行。

注意开启邮箱授权码而非登录密码,防止认证失败。附件名称需符合规范,避免乱码。

异常处理与日志记录

捕获网络超时、文件不存在等异常,记录错误信息以便排查。

若发送失败,检查网络连接或邮箱服务状态。日志输出包含具体错误类型,便于定位问题。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表