使用Python實現(xiàn)自動化辦公的代碼示例(郵件、excel)
一、Python 自動化辦公的準(zhǔn)備工作
1.1 安裝必要的庫
在實現(xiàn)自動化辦公之前,需要安裝相關(guān)庫。以下是常用的 Python 庫:
- 郵件自動化:
smtplib
(發(fā)送郵件),imaplib
(接收郵件),email
(處理郵件內(nèi)容)。 - Excel 操作:
openpyxl
(操作 Excel 文件),pandas
(數(shù)據(jù)處理)。 - 環(huán)境配置:
dotenv
(管理環(huán)境變量)。
安裝方式如下:
pip install openpyxl pandas python-dotenv
1.2 設(shè)置郵件服務(wù)
為了能夠發(fā)送和接收郵件,需要:
- 確保郵箱已開啟 SMTP(發(fā)送)和 IMAP(接收)服務(wù)。
- 使用支持授權(quán)的 App 密鑰(如 Gmail 的“應(yīng)用專用密碼”)。
二、郵件自動化處理
2.1 發(fā)送郵件
示例代碼
以下代碼實現(xiàn)了通過 SMTP 發(fā)送郵件:
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): # 創(chuàng)建郵件對象 msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = recipient_email msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) # 連接到 SMTP 服務(wù)器并發(fā)送郵件 try: with smtplib.SMTP('smtp.gmail.com', 587) as server: server.starttls() server.login(sender_email, sender_password) server.send_message(msg) print("郵件發(fā)送成功!") except Exception as e: print(f"郵件發(fā)送失?。簕e}") # 調(diào)用示例 send_email( sender_email='your_email@gmail.com', sender_password='your_app_password', recipient_email='recipient@example.com', subject='測試郵件', body='這是一封通過 Python 發(fā)送的測試郵件。' )
注意事項
- Gmail 用戶需開啟 “允許不安全應(yīng)用訪問” 或生成 App 密碼。
- 替換 SMTP 服務(wù)地址時,其他郵箱服務(wù)商可能需要不同配置:
- QQ 郵箱:smtp.qq.com
- Outlook:smtp.office365.com
2.2 接收和讀取郵件
示例代碼
以下代碼展示如何通過 IMAP 讀取未讀郵件:
import imaplib import email def fetch_emails(email_address, password): try: # 連接 IMAP 服務(wù)器 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"發(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"內(nèi)容: {part.get_payload(decode=True).decode()}") else: print(f"內(nèi)容: {msg.get_payload(decode=True).decode()}") except Exception as e: print(f"郵件讀取失?。簕e}") # 調(diào)用示例 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 # 讀取數(shù)據(jù) 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]) # 寫入數(shù)據(jù) sheet['A6'] = '新數(shù)據(jù)' workbook.save('example_updated.xlsx') print("Excel 文件已更新!")
3.2 數(shù)據(jù)處理和分析
示例代碼
使用 pandas
對 Excel 數(shù)據(jù)進(jìn)行分析:
import pandas as pd # 讀取 Excel 文件 data = pd.read_excel('example.xlsx') # 打印前五行數(shù)據(jù) print(data.head()) # 數(shù)據(jù)處理 data['總分'] = data['數(shù)學(xué)'] + data['英語'] + data['科學(xué)'] print(data) # 保存結(jié)果 data.to_excel('processed.xlsx', index=False) print("數(shù)據(jù)處理完成并已保存!")
四、綜合實例:從郵件中讀取 Excel 附件并分析
以下代碼展示了一個完整的自動化工作流:
- 接收郵件并提取附件。
- 讀取 Excel 數(shù)據(jù),進(jìn)行分析。
- 將結(jié)果發(fā)送回發(fā)件人。
示例代碼
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}") # 處理附件數(shù)據(jù) data = pd.read_excel(file_path) data['總分'] = data.sum(axis=1) processed_path = 'processed.xlsx' data.to_excel(processed_path, index=False) print("數(shù)據(jù)處理完成") # 返回處理結(jié)果 send_email( sender_email=email_address, sender_password=password, recipient_email=msg['from'], subject='數(shù)據(jù)處理結(jié)果', 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) # 發(fā)送郵件 with smtplib.SMTP('smtp.gmail.com', 587) as server: server.starttls() server.login(sender_email, sender_password) server.send_message(msg) print("郵件已發(fā)送!") # 調(diào)用示例 fetch_and_process_email('your_email@gmail.com', 'your_app_password')
到此這篇關(guān)于使用Python實現(xiàn)自動化辦公的代碼示例(郵件、excel)的文章就介紹到這了,更多相關(guān)Python自動化辦公內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PyQt5實現(xiàn)無邊框窗口的標(biāo)題拖動和窗口縮放
這篇文章主要為大家詳細(xì)介紹了PyQt5實現(xiàn)無邊框窗口的標(biāo)題拖動和窗口縮放,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04分享python中matplotlib指定繪圖顏色的八種方式
這篇文章主要給大家分享的是python中matplotlib指定繪圖顏色的八種方式,在使用matplotlib的pyplot庫進(jìn)行繪圖時,經(jīng)常會發(fā)現(xiàn)各種開源代碼指定“color”的方式并不一致,下面就向大家展示8種指定color的方式,需要的朋友可以參考一下2022-03-03基于Django框架利用Ajax實現(xiàn)點贊功能實例代碼
點贊這個功能是我們現(xiàn)在經(jīng)常會遇到的一個功能,下面這篇文章主要給大家介紹了關(guān)于基于Django框架利用Ajax實現(xiàn)點贊功能的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08python提效小工具之統(tǒng)計xmind用例數(shù)量(源碼)
這篇文章主要介紹了python提效小工具之統(tǒng)計xmind用例數(shù)量,利用python開發(fā)小工具,實現(xiàn)同一份xmind文件中一個或多個sheet頁的用例數(shù)量統(tǒng)計功能,需要的朋友可以參考下2022-10-10PyCharm MySQL可視化Database配置過程圖解
這篇文章主要介紹了PyCharm MySQL可視化Database配置過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06Python如何通過內(nèi)存管理提升程序執(zhí)行效率
Python提供了自動內(nèi)存管理的功能,但是如果不小心使用,可能會導(dǎo)致內(nèi)存泄漏和性能問題,所以巧妙使用內(nèi)存管理是提高Python執(zhí)行效率的關(guān)鍵,下面就來和大家仔細(xì)講講Python的內(nèi)存管理技巧吧2023-06-06