熱線電話:13121318867

登錄
首頁精彩閱讀實戰|用Python制作郵箱自動回復機器人
實戰|用Python制作郵箱自動回復機器人
2021-02-23
收藏


來源:早起Python

作者:陳熹

大家好,又來到Python辦公自動化專題。

在之前的系列文章中,我們已經講解了如何利用Python讀取、收發、管理郵件。本文將進一步分享如何用Python制作一個郵件自動回復機器人。

比如當發送標題為“來句詩”時,能夠自動返回一句詩;當發送郵件標題為“xx(城市)天氣”如“廣州天氣”時,能夠返回所需城市的天氣情況等等,更多功能可以自己定義,主要將涉及

“imbox 讀取及解析附件yagmail 發送郵件郵件與爬蟲的結合”

一、思路分析

和之前的文章類似,我們首先整理下思路,然后逐個解決,簡單來說這個需求可以分為下面的步驟:

“定時讀取未讀郵件,如有則獲取標題及發件人如果標題為“來句詩”,則從“今日詩詞”的網站上獲取一句詩;如果標題為“xx(城市)天氣”則從在線天氣預報網站中獲取相應城市的天氣情況和溫度將獲取的信息組合成新郵件發送會指定收件人將未讀郵件標為已讀”

基本邏輯很簡單,需要用到的知識點我們之前的文章中都有提過,可以直接嘗試完成這個案例。兩個子需求爬取的網站分別是 今日詩詞:https://www.jinrishici.com 和 中國天氣網:http://wthrcdn.etouch.cn/weather_mini?city={城市}

二、代碼實現

郵箱方面,之前我們講過qq郵箱、網易郵箱、這次再換個郵箱(88郵箱),首先通過 imbox 庫解析郵件,可以通過 kering 庫獲取預先存在本地的系統密鑰(本文以 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=Trueas imbox: 
    unread_inbox_messages = imbox.messages(unread = True# 獲取未讀郵件    pass

根據需求自然而然可以想到是反復獲取未讀郵件,解析其標題觀察是否符合條件,符合相應條件則執行相應的函數,并將函數返回的內容組裝成新的郵件。最后無論是否符合要求都將其標記為已讀。

當然,如果要持續運行就還需要將核心代碼包裝成函數,并放在循環體內部。循環可以間隔10分鐘。代碼如下所示:

import keyring from imbox import Imboximport time
password = keyring.get_password('88mail''test@88.com')def get_verse():    
passdef get_weather():    passdef send_mail(email, results):    passdef main():    
with Imbox('imap.88.com'
'test@88.com', password, ssl=Trueas 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)

發送郵件可以利用之前介紹的 yagmail 庫,核心代碼 mail.send 接收收件人郵箱、郵件標題、郵件內容三個參數:

import yagmail# 用服務器、用戶名、密碼實例化郵件mail = yagmail.SMTP(user='xxx@88.com', password = 
password, host='smtp.88.com'# 待發送的內容contents = ['第一段內容''第二段內容']
發送郵件mail.send('收件人郵箱''郵件標題', contents) 

由于 send_mail 函數接受爬蟲返回的 results 作為內容,也獲取了 imbox 解析后得到的特定發件人郵箱,因此可以寫成如下形式:

import yagmaildef send_mail(email, results):    
mail = yagmail.SMTP(user='test@88.com', password=password, host='smtp.88.com')
    contents = [results]
    mail.send(email, '【自動回復】您要的信息見正文', contents)

問題只剩下如何獲取每日一句以及如何獲取指定城市天氣了,首先看一下每日一句的網站特點(實際上這個網站有 API 接口,讀者可以自行嘗試):

實戰|用Python制作郵箱自動回復機器人


先試試直接返回網站內容:

import requests

url = 'https://www.jinrishici.com/'response = requests.get(url).textprint(response)
實戰|用Python制作郵箱自動回復機器人


可以返回內容,沒有特別的反爬措施,但返回的正文是亂碼,同時我們也注意到 utf-8 編碼,因此直接修改編碼即可:

import requests

response = requests.get(url)
response.encoding = "UTF-8"print(response.text)
實戰|用Python制作郵箱自動回復機器人

編碼問題解決以后就可以利用 xpath 解析獲取詩句了:

import requests
from lxml import html

url = 'https://www.jinrishici.com/'response = requests.get(url)
response.encoding = "UTF-8"selector = html.fromstring(response.text)
verse = selector.xpath('//*[@id="sentence"]/text()')print(verse)

有趣的是,并沒有按意愿返回詩句,原因是網頁中的詩句是以Ajax動態加載的,而非靜態出現在網頁中。

重新分析網頁 XHR 即可獲取真正的訪問連接 https://v2.jinrishici.com/one.json?client=browser-sdk/1.2&X-User-Token=xxxxxx,Token見下圖:

實戰|用Python制作郵箱自動回復機器人

分析好原因后代碼反而更加簡單了:

import requests

url = 'https://v2.jinrishici.com/one.json?client=browser-sdk/1.2&X-User-Token=xxxxxx'
response = requests.get(url)
print(response.json()['data']['content'])
實戰|用Python制作郵箱自動回復機器人

返回的詩句直接就可以作為函數結果返回,因此代碼又可以寫成:

import requests

def get_verse():
    url = 'https://v2.jinrishici.com/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.etouch.cn/weather_mini?city=廣州'response = requests.get(url)print(response.json())
實戰|用Python制作郵箱自動回復機器人

根據返回的 json 數據很容易獲取今日的天氣情況和最高最低氣溫,組合成函數效果如下:

def get_weather(city):
    url = f'http://wthrcdn.etouch.cn/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]}度'

至此,代碼部分就寫完了。我們的郵箱自動回復機器人也就擁有了兩個簡單的功能,當然你可以結合自己的需求實現更多有意思的功能!最后附上完整代碼供大家學習與交流

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.jinrishici.com/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.etouch.cn/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)

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢