大家好,又來(lái)到Python辦公自動(dòng)化專題。
在之前的系列文章中,我們已經(jīng)講解了如何利用Python讀取、收發(fā)、管理郵件。本文將進(jìn)一步分享如何用Python制作一個(gè)郵件自動(dòng)回復(fù)機(jī)器人。
比如當(dāng)發(fā)送標(biāo)題為“來(lái)句詩(shī)”時(shí),能夠自動(dòng)返回一句詩(shī);當(dāng)發(fā)送郵件標(biāo)題為“xx(城市)天氣”如“廣州天氣”時(shí),能夠返回所需城市的天氣情況等等,更多功能可以自己定義,主要將涉及
“
”
思路分析
和之前的文章類似,我們首先整理下思路,然后逐個(gè)解決,簡(jiǎn)單來(lái)說(shuō)這個(gè)需求可以分為下面的步驟:
“- 定時(shí)讀取未讀郵件,如有則獲取標(biāo)題及發(fā)件人
- 如果標(biāo)題為“來(lái)句詩(shī)”,則從“今日詩(shī)詞”的網(wǎng)站上獲取一句詩(shī);如果標(biāo)題為“xx(城市)天氣”則從在線天氣預(yù)報(bào)網(wǎng)站中獲取相應(yīng)城市的天氣情況和溫度
- 將獲取的信息組合成新郵件發(fā)送會(huì)指定收件人
”
基本邏輯很簡(jiǎn)單,需要用到的知識(shí)點(diǎn)我們之前的文章中都有提過(guò),可以直接嘗試完成這個(gè)案例。兩個(gè)子需求爬取的網(wǎng)站分別是 今日詩(shī)詞:https://www.
和 中國(guó)天氣網(wǎng):http://wthrcdn./weather_mini?city={城市}
代碼實(shí)現(xiàn)
郵箱方面,之前我們講過(guò)qq郵箱、網(wǎng)易郵箱、這次再換個(gè)郵箱(88郵箱),首先通過(guò) imbox
庫(kù)解析郵件,可以通過(guò) kering
庫(kù)獲取預(yù)先存在本地的系統(tǒng)密鑰(本文以 88 郵箱為例):
import keyring
from imbox import Imbox
password = keyring.get_password('88mail', 'test@88.com')
with Imbox('imap.88.com', 'test@88.com', password, ssl=True) as imbox:
unread_inbox_messages = imbox.messages(unread = True) # 獲取未讀郵件
pass
根據(jù)需求自然而然可以想到是反復(fù)獲取未讀郵件,解析其標(biāo)題觀察是否符合條件,符合相應(yīng)條件則執(zhí)行相應(yīng)的函數(shù),并將函數(shù)返回的內(nèi)容組裝成新的郵件。最后無(wú)論是否符合要求都將其標(biāo)記為已讀。
當(dāng)然,如果要持續(xù)運(yùn)行就還需要將核心代碼包裝成函數(shù),并放在循環(huán)體內(nèi)部。循環(huán)可以間隔10分鐘。代碼如下所示:
import keyring
from imbox import Imbox
import time
password = keyring.get_password('88mail', 'test@88.com')
def get_verse():
pass
def get_weather():
pass
def send_mail(email, results):
pass
def main():
with Imbox('imap.88.com', 'test@88.com', password, ssl=True) as imbox:
unread_inbox_messages = imbox.messages(unread = True) # 獲取未讀郵件
for uid, message in unread_inbox_messages :
title = message.subject
email = message.sent_from[0]['email']
results = ''
if title == '來(lái)句詩(shī)':
results = get_verse()
if title[-2:] == '天氣':
results = get_weather(title[:-2])
if results:
send_mail(email, results)
imbox.mark_seen(uid)
while True:
main()
time.sleep(600)
發(fā)送郵件可以利用之前介紹的 yagmail
庫(kù),核心代碼 mail.send
接收收件人郵箱、郵件標(biāo)題、郵件內(nèi)容三個(gè)參數(shù):
import yagmail
# 用服務(wù)器、用戶名、密碼實(shí)例化郵件
mail = yagmail.SMTP(user='xxx@88.com', password = password, host='smtp.88.com')
# 待發(fā)送的內(nèi)容
contents = ['第一段內(nèi)容', '第二段內(nèi)容']
# 發(fā)送郵件
mail.send('收件人郵箱', '郵件標(biāo)題', contents)
由于 send_mail
函數(shù)接受爬蟲返回的 results
作為內(nèi)容,也獲取了 imbox
解析后得到的特定發(fā)件人郵箱,因此可以寫成如下形式:
import yagmail
def send_mail(email, results):
mail = yagmail.SMTP(user='test@88.com', password=password, host='smtp.88.com')
contents = [results]
mail.send(email, '【自動(dòng)回復(fù)】您要的信息見正文', contents)
問(wèn)題只剩下如何獲取每日一句以及如何獲取指定城市天氣了,首先看一下每日一句的網(wǎng)站特點(diǎn)(實(shí)際上這個(gè)網(wǎng)站有 API 接口,讀者可以自行嘗試):
先試試直接返回網(wǎng)站內(nèi)容:
import requests
url = 'https://www./'
response = requests.get(url).text
print(response)

可以返回內(nèi)容,沒(méi)有特別的反爬措施,但返回的正文是亂碼,同時(shí)我們也注意到 utf-8
編碼,因此直接修改編碼即可:
import requests
response = requests.get(url)
response.encoding = "UTF-8"
print(response.text)
編碼問(wèn)題解決以后就可以利用 xpath 解析獲取詩(shī)句了:
import requests
from lxml import html
url = 'https://www./'
response = requests.get(url)
response.encoding = "UTF-8"
selector = html.fromstring(response.text)
verse = selector.xpath('//*[@id="sentence"]/text()')
print(verse)
有趣的是,并沒(méi)有按意愿返回詩(shī)句,原因是網(wǎng)頁(yè)中的詩(shī)句是以Ajax動(dòng)態(tài)加載的,而非靜態(tài)出現(xiàn)在網(wǎng)頁(yè)中。
重新分析網(wǎng)頁(yè) XHR 即可獲取真正的訪問(wèn)連接 https://v2./one.json?client=browser-sdk/1.2&X-User-Token=xxxxxx
,Token見下圖:
分析好原因后代碼反而更加簡(jiǎn)單了:
import requests
url = 'https://v2./one.json?client=browser-sdk/1.2&X-User-Token=xxxxxx'
response = requests.get(url)
print(response.json()['data']['content'])
返回的詩(shī)句直接就可以作為函數(shù)結(jié)果返回,因此代碼又可以寫成:
import requests
def get_verse():
url = 'https://v2./one.json?client=browser-sdk/1.2&X-User-Token=xxxxxx'
response = requests.get(url)
return f'您要的每日詩(shī)句為:{response.json()["data"]["content"]}'
獲取天氣可以使用官方提供的 API 了,以廣州為例:
import requests
url = 'http://wthrcdn./weather_mini?city=廣州'
response = requests.get(url)
print(response.json())
根據(jù)返回的 json 數(shù)據(jù)很容易獲取今日的天氣情況和最高最低氣溫,組合成函數(shù)效果如下:
def get_weather(city):
url = f'http://wthrcdn./weather_mini?city={city}'
response = requests.get(url).json()
results = response['data']['forecast'][0]
return f'{city}今天的天氣情況為{results["type"]},{results["high"][:-1]}度,{results["low"][:-1]}度'
至此,代碼部分就寫完了。我們的郵箱自動(dòng)回復(fù)機(jī)器人也就擁有了兩個(gè)簡(jiǎn)單的功能,當(dāng)然你可以結(jié)合自己的需求實(shí)現(xiàn)更多有意思的功能!最后附上完整代碼供大家學(xué)習(xí)與交流??
import keyring
import yagmail
from imbox import Imbox
import requests
import time
password = keyring.get_password('88mail', 'test@88.com')
def get_verse():
url = 'https://v2./one.json?client=browser-sdk/1.2&X-User-Token=xxxxxx'
response = requests.get(url)
return f'您要的每日詩(shī)句為:{response.json()["data"]["content"]}'
def get_weather(city):
url = f'http://wthrcdn./weather_mini?city={city}'
response = requests.get(url).json()
results = response['data']['forecast'][0]
return f'{city}今天的天氣情況為{results["type"]},{results["high"][:-1]}度,{results["low"][:-1]}度'
def send_mail(email, results):
mail = yagmail.SMTP(user='test@88.com', password=password, host='smtp.88.com')
contents = [results]
mail.send(email, '【自動(dòng)回復(fù)】您要的信息見正文', contents)
def main():
with Imbox('imap.88.com', 'test@88.com', password, ssl=True) as imbox:
unread_inbox_messages = imbox.messages(unread=True) # 獲取未讀郵件
for uid, message in unread_inbox_messages:
title = message.subject
email = message.sent_from[0]['email']
results = ''
if title == '來(lái)句詩(shī)':
results = get_verse()
if title[-2:] == '天氣':
results = get_weather(title[:-2])
if results:
send_mail(email, results)
imbox.mark_seen(uid)
while True:
main()
time.sleep(600)