当爬取数据后,有时候我们需要发送邮件进行通知,这时可以使用邮件自动发送的方式,当检测到文章更新时,自动抓取并发送。
Paste_Image.png当自己使用时,只需要把Mailhelper()类中的用户名和密码换为自己的,然后,调用
send_mail(self, to_list, sub, content)
就可以直接使用。
import requests
import smtplib
from email.mime.text import MIMEText
from bs4 import BeautifulSoup
class Mailhelper():
def __init__(self):
self.mail_host = "smtp.126.com"
self.mail_user = "xxxxxx@126.com"
self.mail_pass = 'xxxxxxx'
self.port = '25'
def send_mail(self, to_list, sub, content):
me = "Mail Sender" + "<"+ self.mail_user + ">"
msg = MIMEText(content, _subtype='plain', _charset='utf-8')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP(self.mail_host,self.port)
server.connect(self.mail_host)
server.login(self.mail_user,self.mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
print('Done')
except Exception as e:
print(str(e))
return False
if __name__ == '__main__':
mailto_list=['xxxxxx@126.com']
helper = Mailhelper()
url = "http://www.getrandomthings.com"
Soup = BeautifulSoup(requests.get(url).text, 'lxml')
prefixs = Soup.select('a')
textr = []
for prefix in prefixs:
textr.append(prefix.get_text())
textresult = ' '.join(textr)
helper.send_mail(mailto_list, textresult[:17], textresult)
网友评论