網上不少關於發送郵件的代碼都是沒有用的,我用的是126郵箱,會致使報錯554,不少人說這是由於被標記爲垃圾郵件,然而當你改標題改內容後發現……然並卵! 先說一下,此次個人腳本是要定時去爬一個網頁,看是否有內容更新!html
def movie_2045():
tree = tl.getHtmlTrees('http://www.zhuixinfan.com/viewtvplay-977.html',False,'get')
tr_list = tree.xpath('//*[@id="ajax_tbody"]/tr')
if len(tr_list)>2:
#發送郵件
send_email()
複製代碼
tool和setting是我本身寫的工具類和配置類ajax
from tools import Tools as tl
from tools import Settings as st
import schedule
import time
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '個人發送郵箱'
receivers = '個人接收郵箱' # 接收郵件,可設置爲你的QQ郵箱或者其餘郵箱
mail_host="smtp.126.com" #設置服務器
mail_user="個人發送郵箱" #用戶名
mail_pass="" #密碼
def send_email():
# 三個參數:第一個爲文本內容,第二個 plain 設置文本格式,第三個 utf-8 設置編碼
message = MIMEText('咒報2405 我死的理由有更新,連接:http://www.zhuixinfan.com/viewtvplay-977.html', 'plain', 'utf-8')
message['From'] = sender # 發送者
message['To'] = receivers # 接收者
#標題
subject = u'有更新'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP_SSL(mail_host,465)
# smtpObj.set_debuglevel(1)
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
print("郵件發送成功")
except smtplib.SMTPException as e:
print("Error: 沒法發送郵件")
print(e)
複製代碼
最後定時任務我用的是schedule,而不是celerybash
schedule.every(5).seconds.do(movie_2045)
if __name__ == '__main__':
while True:
schedule.run_pending()
time.sleep(1)
複製代碼