# Sending Email Alert When Temperature Exceeds in Raspberry Pi

**send an email when the temperature reaches 32°C or above using a DHT sensor with Raspberry Pi**:

---

# 🔥 Sending Email Alert When Temperature Exceeds 32°C Using Raspberry Pi and DHT11/DHT22

Monitoring temperature is one of the most common use cases for Raspberry Pi-based IoT systems. In this tutorial, we will show you how to use a **DHT11 or DHT22** sensor with Raspberry Pi to read temperature and send an **email alert** when it reaches **32°C or above**.

---

## 🧰 Requirements

* Raspberry Pi (any model with GPIO, e.g., Pi 3/4/Zero W)
    
* DHT11 or DHT22 sensor
    
* Jumper wires
    
* Python 3
    
* Internet connection (for sending emails)
    
* Gmail account (or any SMTP-compatible email)
    

---

## 🔌 Wiring the DHT Sensor

| DHT Pin | Connect to |
| --- | --- |
| VCC | 3.3V |
| Data | GPIO4 (BCM 4) |
| GND | GND |

> ⚠️ Use a 10kΩ resistor between VCC and DATA for DHT22 (optional but recommended for stable readings).

---

## 🐍 Installing Dependencies

1. **Update packages**:
    
    ```bash
    sudo apt update
    sudo apt install python3-pip
    ```
    
2. **Install Adafruit DHT library**:
    
    ```bash
    pip3 install Adafruit_DHT
    ```
    

---

## 📧 Enable Gmail for App Access

If using Gmail:

1. Go to [Google Account Security](https://myaccount.google.com/security)
    
2. Turn **"2-Step Verification"** ON.
    
3. Generate an **App Password**.
    
4. Save that password — it replaces your usual password in code.
    

---

## 💻 Python Script to Monitor Temperature and Send Email

```python
import Adafruit_DHT
import smtplib
from email.mime.text import MIMEText
import time

# Constants
DHT_SENSOR = Adafruit_DHT.DHT11  # Use DHT22 if needed
DHT_PIN = 4                      # GPIO4
ALERT_TEMP = 32.0                # Temperature threshold

# Email config
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
EMAIL_FROM = "your_email@gmail.com"
EMAIL_TO = "receiver_email@gmail.com"
EMAIL_SUBJECT = "Temperature Alert!"
EMAIL_PASSWORD = "your_app_password"  # Use App Password for Gmail

def send_email(temp):
    body = f"Warning! The temperature has reached {temp:.1f}°C."
    msg = MIMEText(body)
    msg["Subject"] = EMAIL_SUBJECT
    msg["From"] = EMAIL_FROM
    msg["To"] = EMAIL_TO

    try:
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()
            server.login(EMAIL_FROM, EMAIL_PASSWORD)
            server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
        print("Email sent!")
    except Exception as e:
        print("Failed to send email:", e)

# Main loop
if __name__ == "__main__":
    alert_sent = False
    try:
        while True:
            humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
            if temperature:
                print(f"Temp={temperature:.1f}°C Humidity={humidity:.1f}%")
                if temperature >= ALERT_TEMP and not alert_sent:
                    send_email(temperature)
                    alert_sent = True
                elif temperature < ALERT_TEMP:
                    alert_sent = False
            else:
                print("Sensor failure. Check wiring.")
            time.sleep(10)
    except KeyboardInterrupt:
        print("Stopped.")
```

---

## 🧪 How It Works

* The script checks temperature every 10 seconds.
    
* If the temperature reaches **32°C or above**, an email is sent.
    
* A flag (`alert_sent`) ensures only one email is sent until the temperature drops below 32 again.
    

---
