先是下載郵件代碼:
import getpass,poplib,sys,email
import re
import os
(host,user)=('pop3.163.com','*@163.com')
passwd="*"
p=poplib.POP3(host)
try:
p.user(user)
p.pass_(passwd)
except poplib.error_proto,e:
print "login failed:",e
sys.exit(1)
status=p.stat()
destfd=open('email.txt',"at")
print "Mail box had %d messages for a total of %d btytes" %(status[0],status[1])
#把所有郵件信息寫入到email.txt文件中
for item in p.list()[1]:
number,octets=item.split(' ')
print "Dwonloading messages %s (%s bytes)" %(number,octets)
lines=p.retr(number)[1]
msg=email.message_from_string("\n".join(lines))
destfd.write(msg.as_string(unixfrom=1))
destfd.write("\n")
destfd.close()
#刪除所有郵件,可以注釋掉
mailmax=status[0]
for i in range(mailmax):
p.dele(i+1)
print p.stat()
p.quit()
分析郵件,提取數據:
import os
import re
file=open('email.txt','r')
count=0
a=[]
log=open('log_email.txt','at')
for line in file.readlines():
#提取Subject: Job的字段,輸出CS_Snapshot
if re.search('Subject: Job',line):
line=re.split('"',line)
log.write("\n")
log.write('_'*40)
log.write(line[1])
log.write('_'*40)
log.write("\n")
elif re.search('Snapshot Change Tracking Result Details',line):
#設置flag
count=1
elif re.search('From',line):
count=0
if count:
#當flag為真的時候,列表a加入匹配的行
if re.search("Target:",line):
a.append(line)
if re.search('bin|lib|config|sh$',line):
#提取字段帶有bin|lib|config或者sh結尾的文件
if len(a):
#當列表a的長度為0,去除a末尾元素,並寫入文件中,這是為了防止設置flag后,其中有些不需要的行業加如到文件中,最后重新給列表設置為空
b=a.pop()
log.write(b)
log.write("\n")
a=[]
log.write(line)
log.write("\n")
file.close()
最后發送郵件:
python popconn.py
python re_email.py
#當log_email.txt 不為空時發送郵件
if [ -s log_email.txt ] ;then
echo "email" |mail -s "subject" -a log_email.txt *@163.com
rm -rf log_email.txt
rm -rf email.txt
else
echo "log_emial is empty file"
fi
總結
pop3登陸郵箱最好不要使用qq郵箱,它有其他操作,比較麻煩。
