前言
通过电脑摄像头拍摄照片,存储为文件,并通过SMTP协议发送邮件
代码
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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| import time import smtplib from email.mime.image import MIMEImage from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import cv2
""" 1、用OpenCV调用摄像头拍照保存图像文件到本地 2、用email库构造邮件内容,保存图片以附件形式插入邮件内容中 3、用smtplib库发送邮件给指定邮箱 """
path = './' sender = '' receiver = '' host = 'smtp.qq.com' pwd = ''
def GetPicture(): cv2.namedWindow('camera',1) cap = cv2.VideoCapture("http://admin:admin@192.168.3.4:8081/video") ret,frame = cap.read() cv2.imwrite(path+'person.jpg',frame) cap.release()
def SetMsg(): msg = MIMEMultipart('mixed') msg['Subject'] = '邮件标题' msg['From'] = sender msg['To'] = receiver
text = '邮件正文' text_plain = MIMEText(text,'plain','utf-8') msg.attach(text_plain)
SendImageFile = open(path+'person.jpg','rb').read() image = MIMEImage(SendImageFile) msg.attach(image)
return msg.as_string()
def SendEmail(msg): """ 发送邮件,首先开启SMTP协议 """ smtp = smtplib.SMTP() smtp.connect(host) smtp.login(sender,pwd) smtp.sendmail(sender,receiver,msg) time.sleep(2) smtp.quit()
if __name__ == '__main__': GetPicture() msg = SetMsg() SendEmail(msg)
|
完成
参考文献
哔哩哔哩——Python编程语言