99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀實(shí)戰(zhàn)|用Python制作郵箱自動回復(fù)機(jī)器人
實(shí)戰(zhàn)|用Python制作郵箱自動回復(fù)機(jī)器人
2021-02-23
收藏


來源:早起Python

作者:陳熹

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

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

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

“imbox 讀取及解析附件yagmail 發(fā)送郵件郵件與爬蟲的結(jié)合”

一、思路分析

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

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

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

二、代碼實(shí)現(xiàn)

郵箱方面,之前我們講過qq郵箱、網(wǎng)易郵箱、這次再換個(gè)郵箱(88郵箱),首先通過 imbox 庫解析郵件,可以通過 kering 庫獲取預(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=Trueas imbox: 
    unread_inbox_messages = imbox.messages(unread = True# 獲取未讀郵件    pass

根據(jù)需求自然而然可以想到是反復(fù)獲取未讀郵件,解析其標(biāo)題觀察是否符合條件,符合相應(yīng)條件則執(zhí)行相應(yīng)的函數(shù),并將函數(shù)返回的內(nèi)容組裝成新的郵件。最后無論是否符合要求都將其標(biāo)記為已讀。

當(dāng)然,如果要持續(xù)運(yùn)行就還需要將核心代碼包裝成函數(shù),并放在循環(huán)體內(nèi)部。循環(huán)可以間隔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)

發(fā)送郵件可以利用之前介紹的 yagmail 庫,核心代碼 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 yagmaildef send_mail(email, results):    
mail = yagmail.SMTP(user='test@88.com', password=password, host='smtp.88.com')
    contents = [results]
    mail.send(email, '【自動回復(fù)】您要的信息見正文', contents)

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

實(shí)戰(zhàn)|用Python制作郵箱自動回復(fù)機(jī)器人


先試試直接返回網(wǎng)站內(nèi)容:

import requests

url = 'https://www.jinrishici.com/'response = requests.get(url).textprint(response)
實(shí)戰(zhàn)|用Python制作郵箱自動回復(fù)機(jī)器人


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

import requests

response = requests.get(url)
response.encoding = "UTF-8"print(response.text)
實(shí)戰(zhàn)|用Python制作郵箱自動回復(fù)機(jī)器人

編碼問題解決以后就可以利用 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)

有趣的是,并沒有按意愿返回詩句,原因是網(wǎng)頁中的詩句是以Ajax動態(tài)加載的,而非靜態(tài)出現(xiàn)在網(wǎng)頁中。

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

實(shí)戰(zhàn)|用Python制作郵箱自動回復(fù)機(jī)器人

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

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'])
實(shí)戰(zhàn)|用Python制作郵箱自動回復(fù)機(jī)器人

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

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())
實(shí)戰(zhàn)|用Python制作郵箱自動回復(fù)機(jī)器人

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

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]}度'

至此,代碼部分就寫完了。我們的郵箱自動回復(fù)機(jī)器人也就擁有了兩個(gè)簡單的功能,當(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.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, '【自動回復(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 == '來句詩':
                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)

數(shù)據(jù)分析咨詢請掃描二維碼

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

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }