Python SMTP在Raspberry Pi上发送重复电子邮件,我使用了PIR

时间:2019-05-23 14:23:41

标签: python-3.x smtp gmail

我正在使用PIR传感器,覆盆子相机:如果检测到运动,请发送带有图片的电子邮件。但是图片和文本一式两份发送。例如,当我收到一封电子邮件时,它附带上一张照片和一张当前照片。我想接收新图片和新文本,而不是上一张图片。

from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
from email.mime.image import MIMEImage

fromaddr = "your email address"    # change the email address accordingly
toaddr = "To email address"        # change the email address accordingly

mail = MIMEMultipart()
mail['From'] = fromaddr
mail['To'] = toaddr
mail['Subject'] = "Intruder Alert!, Motion detected!"
body = "Find the attached for the intruder picture"

PIRSensor = 4

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIRSensor, GPIO.IN, GPIO.PUD_DOWN)

camera = PiCamera()

def capture_image():

    data= time.strftime("%d_%b_%Y|%H:%M:%S")
    camera.start_preview()
    time.sleep(5)
    print data
    camera.capture('/home/pi/Pictures/img%s.png'%data)
    img= '/home/pi/Pictures/img%s.png'%data
    camera.stop_preview()
    time.sleep(1)
    mail.attach(MIMEText(body, 'plain'))
    attachment = open(img, 'rb')
    image=MIMEImage(attachment.read())
    attachment.close()
    mail.attach(image)
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, "your password")
    text = mail.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()

为True时:

    # Read PIR state
    Current_State = GPIO.input(PIRSensor)
    if Current_State==1:
    # PIR is triggered
        print " Intruder Alert!, Motion detected!"

    #Capture Image and send email
        capture_image()

    elif Current_State==0 :
        # PIR has returned to ready state
        print " Ready"

        # Wait for 10 milliseconds
        time.sleep(0.05)

GPIO.cleanup()

0 个答案:

没有答案