python发送邮件
情景:web监控时,若匹配出相应关键字时,把匹配的相关内容放入redis数据库。redis数据库内随着时间推移是不断增加的。功能:实现当redis数据库里的数据增加时,想用户发送一封邮件,提醒查看。
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# -*- coding: UTF-8 -*-
'''
@note: 实现对redis数据库监控功能,有变化发送邮件
'''
import redis
import time
import smtplib
from email.mime.text import MIMEText
red=redis.StrictRedis("172.16.2.156",6379,8)
mailto_list=['1234567@qq.com'] #邮件接收方
mail_host="smtp.163.com"#设置邮件服务器
mail_user="abcd" #用户名
mail_pass="abcd123" #口令
mail_postfix="163.com"#发件箱的后缀
def send_mail(to_list,sub,content):
me="scan_result"+"<"+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,_subtype='plain',_charset='gb2312')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user,mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
def loop():
lis=red.hgetall('alert').values()
num=len(lis)
time.sleep(10)
lis=red.hgetall('alert').values()
num_2=len(lis)
if num==num_2:
print 'no new keyword added......'
else:
if send_mail(mailto_list,"keywords","there have a keyword added ,please check inredis databases......"):
print "send email success......"
else:
print "send email false......"
if __name__ == '__main__':
while True:
try:
loop()
except:
continue
页:
[1]