美文网首页
爬取数据并发送邮件

爬取数据并发送邮件

作者: MingSha | 来源:发表于2017-06-22 16:46 被阅读0次

    当爬取数据后,有时候我们需要发送邮件进行通知,这时可以使用邮件自动发送的方式,当检测到文章更新时,自动抓取并发送。

    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)
    

    相关文章

      网友评论

          本文标题:爬取数据并发送邮件

          本文链接:https://www.haomeiwen.com/subject/qhmfcxtx.html