使用python下载邮件、提取数据并进行发送邮件


先是下载邮件代码:

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邮箱,它有其他操作,比较麻烦。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM