1 #coding:utf-8
 2 import requests
 3 from pyquery import PyQuery as pq
 4 import urllib2, json,sys,smtplib
 5 from email.mime.text import MIMEText
 6 
 7 reload(sys)
 8 sys.setdefaultencoding('utf-8')#避免中文编码问题
 9 
10 
11 mailto_list=["hit_zjw@163.com"]
12 mail_host="smtp.163.com"  #设置服务器
13 mail_user="hit_zjw@163.com"    #用户名
14 mail_pass="zhang130360130"   #口令
15 mail_postfix="163.com"  #发件箱的后缀
16 
17 def send_mail(to_list,sub,contents):
18     #to_list:收件人;sub:主题;content:邮件内容;
19     me=part1+"<"+mail_user+">"  #hello
20     msg = MIMEText(contents,_subtype='plain',_charset='utf-8')#创建一个实例,这里设置为纯文字格式邮件编码utf8
21     msg['Subject'] = sub    #设置主题
22     msg['From'] = me        #设置发件人
23     msg['To'] = ";".join(to_list)
24     try:
25         s = smtplib.SMTP()             #实例化
26         s.connect(mail_host)           #连接smtp服务器
27         s.login(mail_user,mail_pass)   #登陆服务器
28         s.sendmail(me, to_list, msg.as_string()) #发送邮件
29         s.close()
30         return True
31     except Exception, e:
32         print str(e)
33         return False
34 if __name__ == '__main__':
35     str=""
36     url = 'http://news.hitwh.edu.cn/'
37     r = requests.get(url)
38     r.encoding='utf-8'
39     p = pq(r.text).find('#news_list li>a')
40     for b in p:
41         content1=pq(b).text()#获取新闻标题
42         print content1
43         content2='http://news.hitwh.edu.cn/'+pq(b).attr('href')#获取新闻地址
44         print content2
45 
46         str=str+content1+'\n'+content2+'\n'
47         #print content
48     part1 = '工大新闻  from  ZJW'
49     #print str
50     if send_mail(mailto_list,part1,str):
51         print "send msg succeed"
52     else:
53         print "send msg failed"
54 else:
55     print "get joke error"

 

posted on 2016-04-28 12:34  xiao白学编程  阅读(316)  评论(0编辑  收藏  举报