Python邮件提醒脚本
2月份之前,iPhone官网货源不是很足,所以写了个提醒脚本,定时刷新页面,条件符合则发送邮件提醒,
第一次用Python干了点事,Python的简洁、开发效率、丰富的库,给我留下很深印象
1 #!/usr/bin/python
2 #-*- coding:utf-8 -*-
3 #import sys
4 import httplib
5 import smtplib
6 import time
7
8
9 #read mailing list from specified file
10 def read_mailing_list(filename):
11 mailing_list = []
12 f = file(filename, 'r')
13 while True:
14 line = f.readline();
15 if len(line) > 0:
16 mailing_list.append(line.strip())
17 else:
18 break
19 f.close()
20 return mailing_list;
21
22
23 #check if there is some iphone to buy
24 def check_iphone_status(resp_content):
25 s = '预计发货时间'
26 pos = resp_content.find(s)
27 if pos != -1:
28 tag1 = '<span>'
29 tag2 = '</span>'
30 pos1 = resp_content.find(tag1, pos)
31 pos2 = resp_content.find(tag2, pos)
32 if pos1 != -1 and pos2 != -1:
33 dst = resp_content[pos1 + len(tag1) : pos2]
34 dst = ''.join(dst.split())
35 #print dst
36 if dst == '暂无供应':
37 #print 'no iPhone 4S'
38 return -1
39 else:
40 print 'hello, iPhone 4S'
41 return 0
42 else:
43 return -1
44 else:
45 return -1
46
47
48 #send mail
49 def send_mail(_from, _to, _msg):
50 mailsrv = smtplib.SMTP('smtp.163.com')
51 mailsrv.login('xxx', 'xxxxxx')
52 #mailsrv.ehlo()
53 #mailsrv.starttls()
54 #mailsrv.ehlo()
55 mailsrv.sendmail(_from, _to, _msg)
56 mailsrv.quit()
57
58
59 #script start to run
60 #read mailing list
61 mailing_list = read_mailing_list('mailing_list')
62 print 'mailing list: ' , mailing_list
63 mail_from = 'xxxx@163.com'
64 #mail_to = ','.join(mailing_list)
65 mail_msg = 'Subject:iPhone 4S in sale\n\nplease visit:\n \
66 http://www.apple.com.cn\n \
67 http://store.apple.com/cn\n \
68 http://store.apple.com/cn/browse/home/shop_iphone/family/iphone'
69 mail_msg2 = 'Subject:iPhone 4S sell out\n\nplease visit:\n \
70 http://www.apple.com.cn\n \
71 http://store.apple.com/cn\n \
72 http://store.apple.com/cn/browse/home/shop_iphone/family/iphone'
73
74 f = file('log', 'w')
75 f.write('mailing list:\n')
76 for item in mailing_list:
77 f.write(item + '\n')
78 print item
79 f.write('\n')
80 f.flush()
81
82 #send http request
83 while True:
84 conn = httplib.HTTPConnection('store.apple.com')
85 conn.request('GET', '/cn/browse/home/shop_iphone/family/iphone/iphone4s')
86 result = conn.getresponse()
87 resp_status = result.status
88 if resp_status == 200:
89 resp_content = result.read()
90 status = check_iphone_status(resp_content)
91 if status == 0:
92 #send_mail(mail_from, mailing_list, mail_msg)
93 f.write('iPhone 4S in sale\n')
94 f.flush()
95 print 'iPhone 4S in sale'
96 else:
97 #send_mail(mail_from, mailing_list, mail_msg2)
98 #print 'send mail done'
99 f.write('iPhone 4S sell out\n')
100 f.flush()
101 print 'iPhone 4S sell out'
102 conn.close()
103 time.sleep(60)
104
105 f.close()
以上是 Python邮件提醒脚本 的全部内容, 来源链接: utcz.com/z/386770.html