使用Python實(shí)現(xiàn)自動(dòng)化辦公的代碼示例(郵件、excel)
一、Python 自動(dòng)化辦公的準(zhǔn)備工作
1.1 安裝必要的庫(kù)
在實(shí)現(xiàn)自動(dòng)化辦公之前,需要安裝相關(guān)庫(kù)。以下是常用的 Python 庫(kù):
- 郵件自動(dòng)化:
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ā)送和接收郵件,需要:
- 確保郵箱已開(kāi)啟 SMTP(發(fā)送)和 IMAP(接收)服務(wù)。
- 使用支持授權(quán)的 App 密鑰(如 Gmail 的“應(yīng)用專用密碼”)。
二、郵件自動(dòng)化處理
2.1 發(fā)送郵件
示例代碼
以下代碼實(shí)現(xiàn)了通過(guò) 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)建郵件對(duì)象
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='測(cè)試郵件',
body='這是一封通過(guò) Python 發(fā)送的測(cè)試郵件。'
)注意事項(xiàng)
- Gmail 用戶需開(kāi)啟 “允許不安全應(yīng)用訪問(wèn)” 或生成 App 密碼。
- 替換 SMTP 服務(wù)地址時(shí),其他郵箱服務(wù)商可能需要不同配置:
- QQ 郵箱:smtp.qq.com
- Outlook:smtp.office365.com
2.2 接收和讀取郵件
示例代碼
以下代碼展示如何通過(guò) 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 自動(dòng)化處理
3.1 讀取和寫(xiě)入 Excel 文件
示例代碼
使用 openpyxl 讀取和寫(xiě)入 Excel:
import openpyxl
# 打開(kāi) 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])
# 寫(xiě)入數(shù)據(jù)
sheet['A6'] = '新數(shù)據(jù)'
workbook.save('example_updated.xlsx')
print("Excel 文件已更新!")3.2 數(shù)據(jù)處理和分析
示例代碼
使用 pandas 對(duì) 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['英語(yǔ)'] + data['科學(xué)']
print(data)
# 保存結(jié)果
data.to_excel('processed.xlsx', index=False)
print("數(shù)據(jù)處理完成并已保存!")四、綜合實(shí)例:從郵件中讀取 Excel 附件并分析
以下代碼展示了一個(gè)完整的自動(dòng)化工作流:
- 接收郵件并提取附件。
- 讀取 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='附件已處理,請(qǐng)查看。',
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實(shí)現(xiàn)自動(dòng)化辦公的代碼示例(郵件、excel)的文章就介紹到這了,更多相關(guān)Python自動(dòng)化辦公內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決python爬蟲(chóng)中有中文的url問(wèn)題
今天小編就為大家分享一篇解決python爬蟲(chóng)中有中文的url問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
PyQt5實(shí)現(xiàn)無(wú)邊框窗口的標(biāo)題拖動(dòng)和窗口縮放
這篇文章主要為大家詳細(xì)介紹了PyQt5實(shí)現(xiàn)無(wú)邊框窗口的標(biāo)題拖動(dòng)和窗口縮放,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04
分享python中matplotlib指定繪圖顏色的八種方式
這篇文章主要給大家分享的是python中matplotlib指定繪圖顏色的八種方式,在使用matplotlib的pyplot庫(kù)進(jìn)行繪圖時(shí),經(jīng)常會(huì)發(fā)現(xiàn)各種開(kāi)源代碼指定“color”的方式并不一致,下面就向大家展示8種指定color的方式,需要的朋友可以參考一下2022-03-03
Python Trie樹(shù)實(shí)現(xiàn)字典排序
Trie樹(shù)是一種很常用的樹(shù)結(jié)構(gòu),它被廣泛用于各個(gè)方面,比如字符串檢索、中文分詞、求字符串最長(zhǎng)公共前綴和字典排序等等,而且在輸入法中也能看到Trie樹(shù)的身影2014-03-03
基于Django框架利用Ajax實(shí)現(xiàn)點(diǎn)贊功能實(shí)例代碼
點(diǎn)贊這個(gè)功能是我們現(xiàn)在經(jīng)常會(huì)遇到的一個(gè)功能,下面這篇文章主要給大家介紹了關(guān)于基于Django框架利用Ajax實(shí)現(xiàn)點(diǎn)贊功能的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08
python提效小工具之統(tǒng)計(jì)xmind用例數(shù)量(源碼)
這篇文章主要介紹了python提效小工具之統(tǒng)計(jì)xmind用例數(shù)量,利用python開(kāi)發(fā)小工具,實(shí)現(xiàn)同一份xmind文件中一個(gè)或多個(gè)sheet頁(yè)的用例數(shù)量統(tǒng)計(jì)功能,需要的朋友可以參考下2022-10-10
PyCharm MySQL可視化Database配置過(guò)程圖解
這篇文章主要介紹了PyCharm MySQL可視化Database配置過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
Python如何通過(guò)內(nèi)存管理提升程序執(zhí)行效率
Python提供了自動(dòng)內(nèi)存管理的功能,但是如果不小心使用,可能會(huì)導(dǎo)致內(nèi)存泄漏和性能問(wèn)題,所以巧妙使用內(nèi)存管理是提高Python執(zhí)行效率的關(guān)鍵,下面就來(lái)和大家仔細(xì)講講Python的內(nèi)存管理技巧吧2023-06-06

