使用树莓派将摄像头模块采集的图片通过邮件发送

  • 内容
  • ....
  • 相关

在本文中,我们将演示如何使用树莓派3B、运动检测模块和摄像头模块采集图片,然后通过Python语言编程后发送到预设的电子邮件,以此实现一些简单的监控功能。

文中将使用一个运动检测传感器模块,无论它何时检测到物体运动,树莓派相机模块都会拍照并发送带有照片的邮件到指定邮箱。

本教程仅适用于Gmail帐户,因此在继续阅读之前,请确保您有一个Gmail帐户。建议创建一个全新的Gmail帐户,以避免产生任何可能发生的安全问题。

调整Gmail中的默认设置

默认情况下,谷歌是不允许发送包含Python代码的电子邮件的。要更新此默认设置,请按以下步骤在帐户设置中打开“ Allow less secure apps ( 允许不安全的应用 )”:

  1. 登录到您的Gmail帐户。
  2. 点击你的个人头像图片,然后点击“ Google account ” 。
  3. 在 “Sign-in and Security”下面,点击 “Connected apps and sites”。
  4. 点击“ Allow less secure apps ”打开它。

现在您就可以使用您的Gmail登录信息来接收包含Python代码的电子邮件了!

将运动传感器连接到树莓派

将运动传感器的VCC和GND引脚连接到树莓派的5V和GND上,再将运动传感器的OUT引脚连接到GPIO 17上。确保您已经将摄像头模块连接到树莓派上,并且已经从设置选项中打开了相机。


将运动传感器连接到树莓派

关于摄像头模块的使用,可查阅:https://www.basemu.com/how-to-rpi-camera%ef%bc%88b%ef%bc%89rev2-0.html

发送电子邮件的Python代码

在运行代码之前,请确保输入了发送方和接收方的电子邮件地址以及电子邮件发送方的密码。代码将读取传感器的输出,在检测到运动后,将捕获图像并将其保存到数据库文件夹中。当第一次运行该代码时,代码将自动创建文件夹。一旦摄像头捕捉到图像,图像将被附加在电子邮件中并发送到指定地址。

import os
import glob
import picamera
import RPi.GPIO as GPIO
import smtplib
from time import sleep

# Importing modules for sending mail
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders

sender = 'example@gmail.com'
password = 'abcd1234'
receiver = 'example@gmail.com'

DIR = './Database/'
FILE_PREFIX = 'image'
            
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN)  # Read output from PIR motion sensor

def send_mail():
    print 'Sending E-Mail'
    # Create the directory if not exists
    if not os.path.exists(DIR):
        os.makedirs(DIR)
    # Find the largest ID of existing images.
    # Start new images after this ID value.
    files = sorted(glob.glob(os.path.join(DIR, FILE_PREFIX + '[0-9][0-9][0-9].jpg')))
    count = 0
    
    if len(files) > 0:
        # Grab the count from the last filename.
        count = int(files[-1][-7:-4])+1

    # Save image to file
    filename = os.path.join(DIR, FILE_PREFIX + '%03d.jpg' % count)
    # Capture the face
    with picamera.PiCamera() as camera:
        pic = camera.capture(filename)
    # Sending mail
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = 'Movement Detected'
    
    body = 'Picture is Attached.'
    msg.attach(MIMEText(body, 'plain'))
    attachment = open(filename, 'rb')
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename= %s' % filename)
    msg.attach(part)
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(sender, password)
    text = msg.as_string()
    server.sendmail(sender, receiver, text)
    server.quit()

while True:
    i = GPIO.input(11)
    if i == 0:  # When output from motion sensor is LOW
        print "No intruders", i
        sleep(0.3)
    elif i == 1:  # When output from motion sensor is HIGH
        print "Intruder detected", i
        send_mail()

代码分析

首先,我们添加这个项目所需的包和模块。GPIO包有助于控制树莓派的GPIO引脚。Picamera包用于树莓派相机,而Smtplib包允许我们设置Gmail服务器。

import os
import glob
import picamera
import RPi.GPIO as GPIO
import smtplib
from time import sleep

我们需要以下四个模块从树莓派发送邮件:

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders

需要添加收件人的邮箱和发件人的邮箱地址和密码,如下图所示:

sender = 'example@gmail.com'
password = 'abcd1234'
receiver = 'example@gmail.com'

然后我们可以设置保存图像的目录路径和文件前缀:

DIR = './Database/'
FILE_PREFIX = 'image'

然后,因为我们将接收传感器的输出,我们声明pin 11为输入。任何GPIO警告都应该被忽略。

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN)  # Read output from PIR motion sensor

在send_mail()函数中,系统将检查数据库目录是否已经创建。如果没有创建,就会创建一个。然后,它会查找图像的ID,并使用新的ID保存新图像。然后,最新的图像将被附加到电子邮件中,并发送到收件人的地址。

def send_mail():
    print 'Sending E-Mail'
    # Create the directory if not exists
    if not os.path.exists(DIR):
        os.makedirs(DIR)
    # Find the largest ID of existing images.
    # Start new images after this ID value.
    files = sorted(glob.glob(os.path.join(DIR, FILE_PREFIX + '[0-9][0-9][0-9].jpg')))
    count = 0

最后, 复制并粘贴完整的代码到一个扩展名为.py的新文件中,例如 motionTest .py,使用命令运行代码: python motionTest.py 至此,项目就完成了,开心地去测试吧!