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

how to send sensor data to the user using email

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

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
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
2
3
4
5
6
7
8
9
10
11
12
13
14
import smtplib

sender = '[email protected]'
receiver = '[email protected]'
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()