Python+摄像头并拍照发邮箱

1,012 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

今天要做的是Python调用摄像头拍照,并且发送到邮箱。

先说一下思路:

1、通过opencv调用摄像头拍照保存图像到本地

2、用email库构造邮件内容,保存图片以附件形式插入邮件内容

3、用smtplib库发送邮件到指定邮箱

4、生成 .exe 文件

导入工具包

import cv2 
 
from email.mime.image imort MIMEImage #用来构造邮件内容的库
 
from email.mime.text import MIMEText
 
from email.mime.multipart import MIMEMultipart
 
import smtplib #发送邮件

上面cv2可以通过pip install opencv-python -i 进行安装,然后其他的都是python自带的,如果没有的话也可以自己用pip安装一下。

def GetPicture():
    """
    拍照保存图像
    """
    #创建一个窗口camera
    cv2.namedWindow('camera',1) #'1' 表示窗口不能随意拖动
    #调用摄像头
    cap = cv2.VideoCapture(0)
    ret,frame = cap.read() #读取摄像头内容
    cv2.imwrite(path+images+".jpg",frame)  #保存到磁盘
 
 
    #释放摄像头
    cap.release()
    #关闭窗口
    cv2.destroyWindow("camera")

上面代码是用cv2对拍照进行保存到本地路径。


def SetMsg():
    '''
    设置邮件格式
    :return:
    '''
    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+images+'.jpg','rb').read()
    image = MIMEImage(SendImageFile)
    image['Content-Disposition'] = 'attachment;filename="people.jpg"'
    msg.attach(image)
    return msg.as_string()
 
def SendEmail(msg):
    '''
    发送邮件
    :msg :邮件内容
    :return
    '''
    try:
        smtp = smtplib.SMTP_SSL(host,port) #创建一个邮件服务
        # smtp.connect(host)
        smtp.login(sender,pwd)
        smtp.sendmail(sender,receiver,msg)
        time.sleep(3)
        smtp.quit() #退出邮件服务
    except smtplib.SMTPException as e:
        print("e")

上面是设置邮件格式和发送邮件功能的完整展示。

欢迎和我讨论有关程序的问题,也可以答疑。关注公众号:诗一样的代码,交一个朋友。