功能说明
每隔一定时间使用摄像头拍摄照片将拍摄的照片保存至本地通过电子邮件,将照片发送至QQ邮箱实现思路
拍摄照片:使用opencv拍摄发送电子邮件:使用SMTP,QQ邮箱需要开启SMTP功能,如下图(请自行百度)将图片嵌入html中,作为邮件内容发送获取系统时间进行判断,到达预设时间后执行拍摄以及发送函数示例代码
#!/usr/bin/env python3# coding: utf-8import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.header import Headerimport cv2def get_picture(cur_tiem):cap = cv2.VideoCapture(0) # 计算机自带的摄像头为0,外部设备为1ret, frame = cap.read() # ret:True/False,代表有没有读到图片 frame:当前截取一帧的图片# cv2.imshow("capture",.jpg frame)filename = './pic/' + cur_tiem + '.jpg'cv2.imwrite(filename, frame)cap.release()# cv2.destroyAllWindows()return framedef send_mail(cur_tiem):sender = '180*****1@'receiver = '180*****1@'subject = 'Picture by the dormitory camera'smtpserver = ''username = '180*****1@'password = "rkru********ifb"msgRoot = MIMEMultipart('related')msgRoot['From'] = Header('your name') # 邮件发送者名字msgRoot['To'] = Header('your name') # 邮件接收者名字msgRoot['Subject'] = 'Picture by the dormitory camera' + cur_tiemmsgText = MIMEText('<b> Images taken with <i>dormitory camera</i> </b>. and this is the image.<br><img src="cid:image1"><br>ok!', 'html', 'utf-8')msgRoot.attach(msgText)filename = './pic/' + cur_tiem + '.jpg'fp = open(filename, 'rb')msgImage = MIMEImage(fp.read())fp.close()msgImage.add_header('Content-ID', '<image1>')msgRoot.attach(msgImage)smtp = smtplib.SMTP()smtp.connect('')smtp.login(username, password)smtp.sendmail(sender, receiver, msgRoot.as_string())smtp.quit()if __name__ == '__main__':# get_picture()# send_mail()import datetimeimport time as tm print("======开始程序======")while True:cur_tiem = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')time = cur_tiem.split()date_hms = time[1].split(":")hour = date_hms[0]mintue = date_hms[1]second = date_hms[2]if second == '00' and int(mintue) % 10 == 0:try:print("Time is" + str(time[1]) + 'try to send email')get_picture(cur_tiem)send_mail(cur_tiem)except:breakelse:tm.sleep(1)
代码说明
设定每隔10分钟拍摄照片照片保存至./pic/
文件夹下,文件名为拍摄时间,例如-05-15 11:40:00.jpg
扩展
使用nohup
命令挂后台,具体操作请自行百度,或参考我的另一篇文章Linux之 nohup命令文件结构如下: