【代码】Python3通过电脑摄像头拍摄照片并发送邮件

前言

通过电脑摄像头拍摄照片,存储为文件,并通过SMTP协议发送邮件

源代码

192.168.0.1:8080:IP摄像头的地址
admin:admin:登录IP摄像头的用户名和密码

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 # pip install opencv-python

"""
1、用OpenCV调用摄像头拍照保存图像文件到本地
2、用email库构造邮件内容,保存图片以附件形式插入邮件内容中
3、用smtplib库发送邮件给指定邮箱
"""

path = './' # 定义图片本地存储路径
sender = '' # 定义发送方
receiver = '' # 定义接收方
host = 'smtp.qq.com' # 定义服务器
pwd = '' # 定义服务器授权码

def GetPicture():
cv2.namedWindow('camera',1)
# 调用电脑摄像头(笔记本自带摄像头)
# cap = cv2.VideoCapture(0)
# 调用IP摄像头(台式机没有摄像头,使用IP摄像头.app拍摄照片)
cap = cv2.VideoCapture("http://admin:[email protected]:8080/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)
# 修改图片附件的名称(可选)
# image['Content-Disposition'] = 'attachment; filename = "图片名称.jpg"'
# 插入到邮件中
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编程语言