大家好,又來到Python辦公自動化專題。
在之前的系列文章中,我們已經(jīng)講解了如何利用Python讀取、收發(fā)、管理郵件。本文將進一步分享如何用Python制作一個郵件自動回復機器人。
比如當發(fā)送標題為“來句詩”時,能夠自動返回一句詩;當發(fā)送郵件標題為“xx(城市)天氣”如“廣州天氣”時,能夠返回所需城市的天氣情況等等,更多功能可以自己定義,主要將涉及
“
”
思路分析
和之前的文章類似,我們首先整理下思路,然后逐個解決,簡單來說這個需求可以分為下面的步驟:
“- 如果標題為“來句詩”,則從“今日詩詞”的網(wǎng)站上獲取一句詩;如果標題為“xx(城市)天氣”則從在線天氣預報網(wǎng)站中獲取相應城市的天氣情況和溫度
”
基本邏輯很簡單,需要用到的知識點我們之前的文章中都有提過,可以直接嘗試完成這個案例。兩個子需求爬取的網(wǎng)站分別是 今日詩詞:https://www.
和 中國天氣網(wǎng):http://wthrcdn./weather_mini?city={城市}
代碼實現(xiàn)
郵箱方面,之前我們講過qq郵箱、網(wǎng)易郵箱、這次再換個郵箱(88郵箱),首先通過 imbox
庫解析郵件,可以通過 kering
庫獲取預先存在本地的系統(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ù)需求自然而然可以想到是反復獲取未讀郵件,解析其標題觀察是否符合條件,符合相應條件則執(zhí)行相應的函數(shù),并將函數(shù)返回的內(nèi)容組裝成新的郵件。最后無論是否符合要求都將其標記為已讀。
當然,如果要持續(xù)運行就還需要將核心代碼包裝成函數(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 == '來句詩':
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
庫,核心代碼 mail.send
接收收件人郵箱、郵件標題、郵件內(nèi)容三個參數(shù):
import yagmail
# 用服務器、用戶名、密碼實例化郵件
mail = yagmail.SMTP(user='xxx@88.com', password = password, host='smtp.88.com')
# 待發(fā)送的內(nèi)容
contents = ['第一段內(nèi)容', '第二段內(nèi)容']
# 發(fā)送郵件
mail.send('收件人郵箱', '郵件標題', 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, '【自動回復】您要的信息見正文', contents)
問題只剩下如何獲取每日一句以及如何獲取指定城市天氣了,首先看一下每日一句的網(wǎng)站特點(實際上這個網(wǎng)站有 API 接口,讀者可以自行嘗試):
先試試直接返回網(wǎng)站內(nèi)容:
import requests
url = 'https://www./'
response = requests.get(url).text
print(response)

可以返回內(nèi)容,沒有特別的反爬措施,但返回的正文是亂碼,同時我們也注意到 utf-8
編碼,因此直接修改編碼即可:
import requests
response = requests.get(url)
response.encoding = "UTF-8"
print(response.text)
編碼問題解決以后就可以利用 xpath 解析獲取詩句了:
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)
有趣的是,并沒有按意愿返回詩句,原因是網(wǎng)頁中的詩句是以Ajax動態(tài)加載的,而非靜態(tài)出現(xiàn)在網(wǎng)頁中。
重新分析網(wǎng)頁 XHR 即可獲取真正的訪問連接 https://v2./one.json?client=browser-sdk/1.2&X-User-Token=xxxxxx
,Token見下圖:
分析好原因后代碼反而更加簡單了:
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ù)結(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'您要的每日詩句為:{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]}度'
至此,代碼部分就寫完了。我們的郵箱自動回復機器人也就擁有了兩個簡單的功能,當然你可以結(jié)合自己的需求實現(xiàn)更多有意思的功能!最后附上完整代碼供大家學習與交流??
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'您要的每日詩句為:{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, '【自動回復】您要的信息見正文', 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 == '來句詩':
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)