如何使用电子邮件将传感器数据发送给用户

时间:2018-07-29 06:05:46

标签: python python-3.x email notifications sensor

我目前正在使用树莓派,并使用DHT11每秒读取一次温度和湿度值。我必须通过电子邮件将通知发送给用户。这是我的代码,它每秒显示一次传感器数据,但我不知道如何向用户发送电子邮件。我只需要在湿度低于40时发送通知即可。

import RPi.GPIO as GPIO
import dht11
import time
import datetime
import os


# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

instance = dht11.DHT11(pin=dht11_pin)

    while True:

        cnt += 1
        if cnt%limit_sec == 0 or cnt == 1:

            result = instance.read()
            if result.is_valid():

                if previous_temperature != result.temperature or previous_humidity != result.humidity:

                    previous_temperature = result.temperature
                    previous_humidity = result.humidity

                    counter += 1
                    rightnow = datetime.datetime.now()

                    if result.humidity>=40:
                        print(str(counter)+". Last valid input: " )
                        print("Date: " + rightnow.strftime("%d/%m/%Y"))
                        print("Time: " + rightnow.strftime("%H:%M:%S"))
                        print("Status: Your plant is on the good condition.")
                        print("Temperature: %d C" % result.temperature)
                        print("Humidity: %d %%" % result.humidity)

                    else:
                        print(str(counter)+". Last valid input: " )
                        print("Date: " + rightnow.strftime("%d/%m/%Y"))
                        print("Time: " + rightnow.strftime("%H:%M:%S"))
                        print("Status: Your plant is on the bad condition. Please open the water supply.")
                        print("Temperature: %d C" % result.temperature)
                        print("Humidity: %d %%" % result.humidity)

            else:
                print "Invalid result!"
                pass

        time.sleep(sleep_time)

1 个答案:

答案 0 :(得分:2)

您可以发送这样的电子邮件:

import smtplib

sender = 'my@address.de'
receiver = 'your@address.com'
msg['Subject'] = 'Humidity below 40'
msg['From'] = sender
msg['To'] = receiver

# e.g. gmail account
s = smtplib.SMTP("smtp.gmail.com", 587)
s.starttls()
s.login('username', 'password')
s.sendmail(sender, [receiver], msg.as_string())
s.close()