ESP8266/Arduino Uno: Send an email by motion detection

Hi,

I hope someone can help me with this. Btw, I´m a newbie at programming :confused:
I´m trying to send an email when motion is detected with a PID.
What have I missed?
It works fine, if I type in “Send it” in the serial monitor, but not with the PID
// JEOR is what I added to the sketch
Thank in advance

/Jens

/

int pirPin = 7;  //JEOR
int pirState = LOW;  //JEOR
int val = 0;                    // JEOR variable for reading the pin status

byte byteRead;


#include <Adafruit_ESP8266.h>
#include <SoftwareSerial.h>

#include <VirtualWire.h>  //JEOR

#define ESP_RX   3
#define ESP_TX   4
#define ESP_RST  8
SoftwareSerial softser(ESP_RX, ESP_TX);

// Must declare output stream before Adafruit_ESP8266 constructor; can be
// a SoftwareSerial stream, or Serial/Serial1/etc. for UART.
Adafruit_ESP8266 wifi(&softser, &Serial, ESP_RST);
// Must call begin() on the stream(s) before using Adafruit_ESP8266 object.

#define ESP_SSID "HomeBox-3F60_2.4G" // Your network name here
#define ESP_PASS "XXXXXXXX" // Your network password here

char EMAIL_FROM[] = "XXXXXXX@xxxx.xxx";
char EMAIL_PASSWORD[] =  "XXXXXXXXXX";
char EMAIL_TO[] = "XXXX@xxxxx.xxx";
char SUBJECT[]  = "-- TEST ALARM --";
char EMAIL_CONTENT[] = "MESSAGE1!,\r\MESSAGE2! MESSAGE3!!";

// We'll need your EMAIL_FROM and its EMAIL_PASSWORD base64 encoded, you can use https://www.base64encode.org/
#define EMAIL_FROM_BASE64 "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
#define EMAIL_PASSWORD_BASE64 "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"

#define HOST     "mail.smtp2go.com"     // Find/Google your email provider's SMTP outgoing server name for unencrypted email

#define PORT     2525                     // Find/Google your email provider's SMTP outgoing port for unencrypted email

int count = 0; // we'll use this int to keep track of which command we need to send next
bool send_flag = false; // we'll use this flag to know when to send the email commands

void setup() {
  char buffer[50];

  // This might work with other firmware versions (no guarantees)
  // by providing a string to ID the tail end of the boot message:
  
  // comment/replace this if you are using something other than v 0.9.2.4!
  wifi.setBootMarker(F("Version:0.9.2.4]\r\n\r\nready"));

  softser.begin(9600); // Soft serial connection to ESP8266
  Serial.begin(57600); while(!Serial); // UART serial debug

  
  Serial.println(F("Adafruit ESP8266 Email"));

  // Test if module is ready
  Serial.print(F("Hard reset..."));
  if(!wifi.hardReset()) {
    Serial.println(F("no response from the module."));
    for(;;);
  }
  Serial.println(F("OK."));

  Serial.print(F("Soft reset..."));
  if(!wifi.softReset()) {
    Serial.println(F("no soft response from module."));
    for(;;);
  }
  Serial.println(F("OK."));

  Serial.print(F("Checking firmware version..."));
  wifi.println(F("AT+GMR"));
  if(wifi.readLine(buffer, sizeof(buffer))) {
    Serial.println(buffer);
    wifi.find(); // Discard the 'OK' that follows
  } else {
    Serial.println(F("error"));
  }

  Serial.print(F("Connecting to WiFi..."));
  if(wifi.connectToAP(F(ESP_SSID), F(ESP_PASS))) {

    // IP addr check isn't part of library yet, but
    // we can manually request and place in a string.
    Serial.print(F("OK\nChecking IP addr..."));
    wifi.println(F("AT+CIFSR"));
    if(wifi.readLine(buffer, sizeof(buffer))) {
        Serial.println(buffer);
        wifi.find(); // Discard the 'OK' that follows

        Serial.print(F("Connecting to host..."));

        Serial.print("Connected..");
        wifi.println("AT+CIPMUX=0"); // configure for single connection, 
                                     //we should only be connected to one SMTP server
        wifi.find();
        wifi.closeTCP(); // close any open TCP connections
        wifi.find();
        Serial.println("Type \"send it\" to send an email");
        
    } else { // IP addr check failed
      Serial.println(F("error"));
    }
  } else { // WiFi connection failed
    Serial.println(F("FAIL"));
  }
  
  {  //JEOR
  
      vw_setup(2000);  //JEOR
     vw_set_tx_pin(3);  //JEOR 
        
     pinMode(pirPin, INPUT);  //JEOR

  
 }  //JEOR
 
  }


void loop() {

    if(!send_flag){ // check if we expect to send an email
        if(Serial.available()){  // there is data in the serial, let's see if the users wants to "send it" [the email]
            if(Serial.find("send it")){  // set the send_flag when the uses types "send it" in the serial monitor.
                Serial.println("Sending email...");
                send_flag = true;
            }
        }
    }

    if(send_flag){ // the send_flat is set, this means we are or need to start sending SMTP commands
        if(do_next()){ // execute the next command
            count++; // increment the count so that the next command will be executed next time.
        }
    }
}

// do_next executes the SMTP command in the order required.
boolean do_next()
{

    switch(count){ 
    case 0:
        Serial.println("Connecting...");
        return wifi.connectTCP(F(HOST), PORT);
        break;
    case 1:
        // send "EHLO ip_address" command. Server will reply with "250" and welcome message
        return wifi.cipSend("EHLO computer.com",F("250")); // ideally an ipaddress should go in place 
                                                           // of "computer.com" but I think the email providers
                                                           // check the IP anyways so I just put anything.                                   
        break;
    case 2:
        // send "AUTH LOGIN" command to the server will reply with "334 username" base 64 encoded
        return wifi.cipSend("AUTH LOGIN",F("334 VXNlcm5hbWU6"));
        break;
    case 3:
        // send username/email base 64 encoded, the server will reply with "334 password" base 64 encoded
        return wifi.cipSend(EMAIL_FROM_BASE64,F("334 UGFzc3dvcmQ6")); 
        break;
    case 4:
        // send password base 64 encoded, upon successful login the server will reply with 235.
        return wifi.cipSend(EMAIL_PASSWORD_BASE64,F("235"));
        break;
    case 5:{
        // send "MAIL FROM:<emali_from@domain.com>" command
        char mailFrom[50] = "MAIL FROM:<"; // If 50 is not long enough change it, do the same for the array in the other cases
        strcat(mailFrom,EMAIL_FROM);
        strcat(mailFrom,">");

        return wifi.cipSend(mailFrom,F("250"));
        break;
    }
    case 6:{
        // send "RCPT TO:<email_to@domain.com>" command
        char rcptTo[50] = "RCPT TO:<";
        strcat(rcptTo,EMAIL_TO);
        strcat(rcptTo,">");
        return wifi.cipSend(rcptTo,F("250"));  
        break;
    }
    case 7:
        // Send "DATA"  command, the server will reply with something like "334 end message with \r\n.\r\n."
        return wifi.cipSend("DATA",F("354"));
        break;
    case 8:{
        // apply "FROM: from_name <from_email@domain.com>" header
        char from[100] = "FROM: ";
        strcat(from,EMAIL_FROM);
        strcat(from," ");
        strcat(from,"<");
        strcat(from,EMAIL_FROM);
        strcat(from,">");
        return wifi.cipSend(from);  
        break;
    }
    case 9:{
        // apply TO header 
        char to[100] = "TO: ";
        strcat(to,EMAIL_TO);
        strcat(to,"<");
        strcat(to,EMAIL_TO);
        strcat(to,">");
        return wifi.cipSend(to);  
        break;
    }
    case 10:{
        // apply SUBJECT header
        char subject[50] = "SUBJECT: ";
        strcat(subject,SUBJECT);
        return wifi.cipSend(subject);
        break;
    }
    case 11:
        return wifi.cipSend("\r\n");   // marks end of header (SUBJECT, FROM, TO, etc);
        break;
    case 12:
        return wifi.cipSend(EMAIL_CONTENT);
        break;
    case 13:
        return wifi.cipSend("\r\n.");  // marks end of data command
        break;
    case 14:
        return wifi.cipSend("QUIT");
        break;
    case 15:
        wifi.closeTCP();
        return true;
        break;
    case 16:
        Serial.println("Done");
        send_flag = false;
        count = 0;
        return false; // we don't want to increment the count
        break;
    default:
        break;
        }


{  //JEOR

   Serial.begin(9600);  //Jeor
  
    pirState = digitalRead(pirPin);  //JEOR
  
  
    if (pirState == HIGH){  //JEOR

         
    const char *msg = "send it";  //JEOR
    vw_send((uint8_t *)msg, strlen(msg));  //JEOR
    vw_wait_tx();  //JEOR
    
   }    //JEOR
    
    }    
}
{  //JEOR

   Serial.begin(9600);  //Jeor

How many times do you need to call Serial.begin()? ANY answer other than ONCE is wrong.

if (pirState == HIGH){  //JEOR

         
    const char *msg = "send it";  //JEOR
    vw_send((uint8_t *)msg, strlen(msg));  //JEOR
    vw_wait_tx();  //JEOR
   
   }    //JEOR

What is the relationship between this code and sending an e-mail?

Thank you Paul,

How many times do you need to call Serial.begin()? ANY answer other than ONCE is wrong.

Yes you are right about that, but there is a Serial.begin(57600); for the serial monitor and then I think I also needed one for this:

if (pirState == HIGH){  //JEOR

         
    const char *msg = "send it";  //JEOR
    vw_send((uint8_t *)msg, strlen(msg));  //JEOR
    vw_wait_tx();  //JEOR
   
   }    //JEOR

const char *msg = "send it";
I belive this is used for VirtualWire, so when the PIR sensor is High on pin 7, it would write the "send it" instead of I´m typing it in the Serial monitor.

I hope it`s giving any sence to you?

Maybe I should mention where i got the codes from.

Wifi:

and

PIR:

and then I think I also needed one for this:

Why? For one thing, the serial port is already setup. For another, that bit of code does NOT use the serial port at all.

I belive this is used for VirtualWire, so when the PIR sensor is High on pin 7, it would write the "send it" instead of I´m typing it in the Serial monitor.

It should. But, it sends that data to a radio. You haven't mentioned actually connecting a radio to the Arduino. Sending "send it" out from the Arduino as a series of radio waves is not going to get anything into the serial buffer, so I don't understand the point of having done that.

It should. But, it sends that data to a radio. You haven't mentioned actually connecting a radio to the Arduino. Sending "send it" out from the Arduino as a series of radio waves is not going to get anything into the serial buffer, so I don't understand the point of having done that.

I´m not sure what you mean.

  {  //JEOR
  
     vw_setup(2000);  //JEOR
     vw_set_tx_pin(3);  //JEOR 
        
   pinMode(pirPin, INPUT);     // declare sensor as input  
   pinMode(ledPin, OUTPUT);      // declare LED as output

   
  
 }  //JEOR

I thought that this would send the command to E8266 by pin 3. (vw_set_tx_pin(3))

Am I totaly wrong here?

Btw, I have changed the code and added an LED på pin 11.
If I only load the code for the PIR and LED to the Arduino, it is working fine.
When I then add the code for the Wifi, then the PIR stopped working.

Here is the new code:

int ledPin = 11;                // choose the pin for the LED
int pirPin = 7;               // choose the input pin (for PIR sensor)

boolean bAlarm = false;

int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status

byte byteRead;

#include <Adafruit_ESP8266.h>
#include <SoftwareSerial.h>

#include <VirtualWire.h>  //JEOR

#define ESP_RX   3
#define ESP_TX   4
#define ESP_RST  8
SoftwareSerial softser(ESP_RX, ESP_TX);

Adafruit_ESP8266 wifi(&softser, &Serial, ESP_RST);
#define ESP_SSID "xxxx" // Your network name here
#define ESP_PASS "xxxxx" // Your network password here

char EMAIL_FROM[] = "xxxxxxx";
char EMAIL_PASSWORD[] =  "xxxxxxx";
char EMAIL_TO[] = "xxxxxx";
char SUBJECT[]  = "-- TEST ALARM --";
char EMAIL_CONTENT[] = "MESSAGE1!,\r\MESSAGE2! MESSAGE3!!";


#define EMAIL_FROM_BASE64 "XXXXXXXXXXXXXXXXXXXXXXXXXXX"
#define EMAIL_PASSWORD_BASE64 "XXXXXXXXXXXXXXXXXXXXXXXXXXX"


#define HOST     "mail.smtp2go.com"     

#define PORT     2525                     

int count = 0; 
bool send_flag = false; 

void setup (){


char buffer[50];
wifi.setBootMarker(F("Version:0.9.2.4]\r\n\r\nready"));
softser.begin(9600); // Soft serial connection to ESP8266
Serial.begin(57600); while(!Serial); // UART serial debug
Serial.println(F("Adafruit ESP8266 Email"));
// Test if module is ready
  Serial.print(F("Hard reset..."));
  if(!wifi.hardReset()) {
    Serial.println(F("no response from the module."));
    for(;;);
  }
  Serial.println(F("OK."));

  Serial.print(F("Soft reset..."));
  if(!wifi.softReset()) {
    Serial.println(F("no soft response from module."));
    for(;;);
  }
  Serial.println(F("OK."));

  Serial.print(F("Checking firmware version..."));
  wifi.println(F("AT+GMR"));
  if(wifi.readLine(buffer, sizeof(buffer))) {
    Serial.println(buffer);
    wifi.find(); // Discard the 'OK' that follows
  } else {
    Serial.println(F("error"));
  }

  Serial.print(F("Connecting to WiFi..."));
  if(wifi.connectToAP(F(ESP_SSID), F(ESP_PASS))) {

    // IP addr check isn't part of library yet, but
    // we can manually request and place in a string.
    Serial.print(F("OK\nChecking IP addr..."));
    wifi.println(F("AT+CIFSR"));
    if(wifi.readLine(buffer, sizeof(buffer))) {
        Serial.println(buffer);
        wifi.find(); // Discard the 'OK' that follows

        Serial.print(F("Connecting to host..."));

        Serial.print("Connected..");
        wifi.println("AT+CIPMUX=0"); // configure for single connection, 
                                     //we should only be connected to one SMTP server
        wifi.find();
        wifi.closeTCP(); // close any open TCP connections
        wifi.find();
        Serial.println("Type \"send it\" to send an email");
        
    } else { // IP addr check failed
      Serial.println(F("error"));
    }
  } else { // WiFi connection failed
    Serial.println(F("FAIL"));
  }



  {  //JEOR
  
     vw_setup(2000);  //JEOR
     vw_set_tx_pin(3);  //JEOR 
        
   pinMode(pirPin, INPUT);     // declare sensor as input  
   pinMode(ledPin, OUTPUT);      // declare LED as output

   
  
 }  //JEOR

}



void loop (){



    if(!send_flag){ // check if we expect to send an email
        if(Serial.available()){  // there is data in the serial, let's see if the users wants to "send it" [the email]
            if(Serial.find("send it")){  // set the send_flag when the uses types "send it" in the serial monitor.
                Serial.println("Sending email...");
                send_flag = true;
            }
        }
    }

    if(send_flag){ // the send_flat is set, this means we are or need to start sending SMTP commands
        if(do_next()){ // execute the next command
            count++; // increment the count so that the next command will be executed next time.
        }
    }
}

// do_next executes the SMTP command in the order required.
boolean do_next()
{

    switch(count){ 
    case 0:
        Serial.println("Connecting...");
        return wifi.connectTCP(F(HOST), PORT);
        break;
    case 1:
        // send "EHLO ip_address" command. Server will reply with "250" and welcome message
        return wifi.cipSend("EHLO computer.com",F("250")); // ideally an ipaddress should go in place 
                                                           // of "computer.com" but I think the email providers
                                                           // check the IP anyways so I just put anything.                                   
        break;
    case 2:
        // send "AUTH LOGIN" command to the server will reply with "334 username" base 64 encoded
        return wifi.cipSend("AUTH LOGIN",F("334 VXNlcm5hbWU6"));
        break;
    case 3:
        // send username/email base 64 encoded, the server will reply with "334 password" base 64 encoded
        return wifi.cipSend(EMAIL_FROM_BASE64,F("334 UGFzc3dvcmQ6")); 
        break;
    case 4:
        // send password base 64 encoded, upon successful login the server will reply with 235.
        return wifi.cipSend(EMAIL_PASSWORD_BASE64,F("235"));
        break;
    case 5:{
        // send "MAIL FROM:<emali_from@domain.com>" command
        char mailFrom[50] = "MAIL FROM:<"; // If 50 is not long enough change it, do the same for the array in the other cases
        strcat(mailFrom,EMAIL_FROM);
        strcat(mailFrom,">");

        return wifi.cipSend(mailFrom,F("250"));
        break;
    }
    case 6:{
        // send "RCPT TO:<email_to@domain.com>" command
        char rcptTo[50] = "RCPT TO:<";
        strcat(rcptTo,EMAIL_TO);
        strcat(rcptTo,">");
        return wifi.cipSend(rcptTo,F("250"));  
        break;
    }
    case 7:
        // Send "DATA"  command, the server will reply with something like "334 end message with \r\n.\r\n."
        return wifi.cipSend("DATA",F("354"));
        break;
    case 8:{
        // apply "FROM: from_name <from_email@domain.com>" header
        char from[100] = "FROM: ";
        strcat(from,EMAIL_FROM);
        strcat(from," ");
        strcat(from,"<");
        strcat(from,EMAIL_FROM);
        strcat(from,">");
        return wifi.cipSend(from);  
        break;
    }
    case 9:{
        // apply TO header 
        char to[100] = "TO: ";
        strcat(to,EMAIL_TO);
        strcat(to,"<");
        strcat(to,EMAIL_TO);
        strcat(to,">");
        return wifi.cipSend(to);  
        break;
    }
    case 10:{
        // apply SUBJECT header
        char subject[50] = "SUBJECT: ";
        strcat(subject,SUBJECT);
        return wifi.cipSend(subject);
        break;
    }
    case 11:
        return wifi.cipSend("\r\n");   // marks end of header (SUBJECT, FROM, TO, etc);
        break;
    case 12:
        return wifi.cipSend(EMAIL_CONTENT);
        break;
    case 13:
        return wifi.cipSend("\r\n.");  // marks end of data command
        break;
    case 14:
        return wifi.cipSend("QUIT");
        break;
    case 15:
        wifi.closeTCP();
        return true;
        break;
    case 16:
        Serial.println("Done");
        send_flag = false;
        count = 0;
        return false; // we don't want to increment the count
        break;
    default:
        break;
        }
{
  
    val = digitalRead(pirPin);  // read input value  JEOR
  if (val == HIGH) {            // check if the input is HIGH   JEOR
    digitalWrite(ledPin, HIGH);  // turn LED ON   JEOR
    delay(1000); //for 1 second  JEOR

    val = digitalRead(pirPin);  // read input value   JEOR
    if (val == HIGH){    //JEOR
      Serial.println("Motion detected");  //JEOR
      const char *msg = "send it";  //JEOR
      vw_send((uint8_t *)msg, strlen(msg));  //JEOR
      vw_wait_tx();  //JEOR
      }  //JEOR
}
    if (pirState == LOW) {      // JEOR
      Serial.println("Movement stopped!");      // We only want to print on the output change, not state   JEOR
      pirState = LOW;  //JEOR
    }  //JEOR
  

  else {  JEOR
    digitalWrite(ledPin, LOW); // turn LED OFF   JEOR
    if (pirState == LOW){      //   JEOR
      Serial.println("LED OFF!");      // We only want to print on the output change, not state   JEOR
      pirState = LOW;   //JEOR

    }   //JEOR

  }   //JEOR
  }   //JEOR
}

I thought that this would send the command to E8266 by pin 3. (vw_set_tx_pin(3))

Am I totaly wrong here?

Yes, you are. The ESP8266 is a serial device. You only send data to it, or get data from it, using an instance of the HardwareSerial class (Serial, Serial1, etc.) or by using an instance of a software serial class (SoftwareSerial, NeoSoftSerial, AltSoftSerial, etc.).

Well, I must admit, that I´m probably not the sharpest knife in the drawer, when it coms to programming :blush:

I haven´t got much time lately, but I managed to figure out, how to send an email, activated by the motion sensor. :smiley: - Maybe there is a better way…?

But, now I got some new issues.

  1. How do I decrease the time when the sensor is activ - or time of digitalRead?
    I only want to set the “send_flag” ones, when motion is detected, but the sensor are keeping the input high for several seconds. Then my mailbox is getting spammed.

  2. When, in this case, the window is closed (switchPin is high). It is not supposed to set the “send_flag” - but it does.

I have tryed to Google it, but with no luck. I hope someone would be so kind to help me with this.

Here is a sample af the new code, I added:

#include <Adafruit_ESP8266.h>
#include <SoftwareSerial.h>

#define ESP_RX   3
#define ESP_TX   4
#define ESP_RST  8
SoftwareSerial softser(ESP_RX, ESP_TX);

int switchPin = 10;   
int switchState = LOW;
int ledPin = 11;      
int sensorPin = 2;    
int sensorValue = 0;  
int val = LOW;    


byte byteRead;

void setup() {

  pinMode(ledPin, OUTPUT);  
  pinMode(sensorPin, INPUT);  
  pinMode(switchPin, INPUT);  


void loop() {

 val = digitalRead(sensorPin);
     if (val == HIGH){
       digitalWrite(ledPin, HIGH);

     }

 val = digitalRead(sensorPin);
     if (val == LOW){
       digitalWrite(ledPin, LOW);

     }
            
    if(!send_flag){ // check if we expect to send an email and close window.
        if(digitalRead(sensorPin)){  // IF Sensor is HIGH we want to send email and close window.
            if(val == HIGH){  // Set the send_flag when the Sensor is activ.
              if(digitalRead(switchPin)); // Window open/closed state.
                if (val == LOW)  // When LOW, the window is open, and we want to set send_flag and close the window. 
                 Serial.println("Motion detected - Sending email and window is closing...");  //Serial monitor info.
                delay(500);  
           //     send_flag = true;
            }
        }
    }

    if(!send_flag){ // check if motion is detedted, but window is closed.
        if(digitalRead(switchPin)){  // Window open/closed state.
            if(val == HIGH){  // When HIGH, the window is closed, and we do not want to set send_flag while the window is closed.
               send_flag = false;
                Serial.println("STOP switch activated - Window is closed - No need til send email...");  //Serial monitor info.
          //      delay(500);  
                send_flag = false;
            }
        }
    }
  1. How do I decrease the time when the sensor is activ - or time of digitalRead?

Which sensor? If you are talking about the PIR sensor, get out your screwdriver and twist the pots on the sensor, to adjust sensitivity and time between tests.

  1. How do I decrease the time when the sensor is activ - or time of digitalRead?
    I only want to set the "send_flag" ones, when motion is detected, but the sensor are keeping the input high for several seconds. Then my mailbox is getting spammed.

Why? The sensor only changes to the "motion is detected" state ONCE. Look at the state change detection example.

SoftwareSerial softser(ESP_RX, ESP_TX);

Can you post a picture of your softser?

Can you post code that will actually compile? Use Tools +
Auto Format first, so that it
doesn't look like
it was typed by a drunken
monkey.

Thanks Paul,

Which sensor? If you are talking about the PIR sensor, get out your screwdriver and twist the pots on the sensor, to adjust sensitivity and time between tests.

Yes, I´m aware of the pots on the PIR sensor. The problem is, when there is movement in front of the sensor for an longer period of time and while the window is closing, I don`t want to keep receiving emails.

Can you post a picture of your softser? Can you post code that will actually compile? Use Tools + Auto Format first, so that it doesn't look like it was typed by a drunken monkey.

Sorry for the "Drunken monkey" code. :smiley: I will post the complete code (with Autoformat) a.s.a.p.

Here is the complete sketch. The interrupt switch (pin 10) seems to work most of the time now. When pin 10 is HIGH, it do not send an email. I have seen, that sometimes, it sends an email anyway. Can’t figure out why. Is there a better way for getting this to work more stable?

When this issue is fixed, my plan is to include an actuator for opening andcloseing a window. For that, I probrably need one more interrupt switch for the actuator.

Looking forward to get some comments on this.

  1. half:
#include <Adafruit_ESP8266.h>
#include <SoftwareSerial.h>

#define ESP_RX   3
#define ESP_TX   4
#define ESP_RST  8
SoftwareSerial softser(ESP_RX, ESP_TX);

int switchPin = 10;   // select the pin for the SWITCH 1  //JEOR
int switchState = LOW;
int ledPin = 11;      // select the pin for the LED  //JEOR
int ledCameOne;
int sensorPin = 2;    // select the input pin for the Pir  //JEOR
int sensorPinValue = 0;  // variable to store the value coming from the sensor  //JEOR
int val = LOW;    //JEOR

byte byteRead;  //JEOR

// Must declare output stream before Adafruit_ESP8266 constructor; can be
// a SoftwareSerial stream, or Serial/Serial1/etc. for UART.
Adafruit_ESP8266 wifi(&softser, &Serial, ESP_RST);
// Must call begin() on the stream(s) before using Adafruit_ESP8266 object.

#define ESP_SSID "XXXXXXXXXX" // Your network name here
#define ESP_PASS "XXXXXXXXXXXXX" // Your network password here

char EMAIL_FROM[] = "ALARM_Vindue@oeris.dk";
char EMAIL_PASSWORD[] =  "XXXXXXXXXXXX";
char EMAIL_TO[] = "XXXXXXXXXXXXXXX";
char SUBJECT[]  = "-- TEST ALARM --";
char EMAIL_CONTENT[] = "xxxxxxxxxxxxxx,\r\nxxxxxxxxxxxxxxxxxxx";

// We'll need your EMAIL_FROM and its EMAIL_PASSWORD base64 encoded, you can use https://www.base64encode.org/
#define EMAIL_FROM_BASE64 "XXXXXXXXXXXXXXXXXXXXXXXXX"
#define EMAIL_PASSWORD_BASE64 "XXXXXXXXXXXXXXXXXXXXX"

#define HOST     "mail.smtp2go.com"     // Find/Google your email provider's SMTP outgoing server name for unencrypted email

#define PORT     2525                     // Find/Google your email provider's SMTP outgoing port for unencrypted email

int count = 0; // we'll use this int to keep track of which command we need to send next
bool send_flag = false; // we'll use this flag to know when to send the email commands

void setup() {

  pinMode(ledPin, OUTPUT);  //JEOR
  pinMode(sensorPin, INPUT);  //JEOR
  pinMode(switchPin, INPUT);  //JEOR


  char buffer[50];

  // This might work with other firmware versions (no guarantees)
  // by providing a string to ID the tail end of the boot message:

  // comment/replace this if you are using something other than v 0.9.2.4!
  wifi.setBootMarker(F("Version:0.9.2.4]\r\n\r\nready"));

  softser.begin(9600); // Soft serial connection to ESP8266
  Serial.begin(57600); while (!Serial); // UART serial debug

  Serial.println(F("Adafruit ESP8266 Email"));

  // Test if module is ready
  Serial.print(F("Hard reset..."));
  if (!wifi.hardReset()) {
    Serial.println(F("no response from the module."));
    for (;;);
  }
  Serial.println(F("OK."));

  Serial.print(F("Soft reset..."));
  if (!wifi.softReset()) {
    Serial.println(F("no soft response from module."));
    for (;;);
  }
  Serial.println(F("OK."));

  Serial.print(F("Checking firmware version..."));
  wifi.println(F("AT+GMR"));
  if (wifi.readLine(buffer, sizeof(buffer))) {
    Serial.println(buffer);
    wifi.find(); // Discard the 'OK' that follows
  } else {
    Serial.println(F("error"));
  }

  Serial.print(F("Connecting to WiFi..."));
  if (wifi.connectToAP(F(ESP_SSID), F(ESP_PASS))) {

    // IP addr check isn't part of library yet, but
    // we can manually request and place in a string.
    Serial.print(F("OK\nChecking IP addr..."));
    wifi.println(F("AT+CIFSR"));
    if (wifi.readLine(buffer, sizeof(buffer))) {
      Serial.println(buffer);
      wifi.find(); // Discard the 'OK' that follows

      Serial.print(F("Connecting to host..."));

      Serial.print("Connected..");
      wifi.println("AT+CIPMUX=0"); // configure for single connection,
      //we should only be connected to one SMTP server
      wifi.find();
      wifi.closeTCP(); // close any open TCP connections
      wifi.find();
      Serial.println("System restarted and ready");

    } else { // IP addr check failed
      Serial.println(F("error"));
    }
  } else { // WiFi connection failed
    Serial.println(F("FAIL"));
  }

}
  1. half:
void loop() {

  val = digitalRead(sensorPin);
  if (val == HIGH) {
    digitalWrite(ledPin, HIGH);

  }

  val = digitalRead(sensorPin);
  if (val == LOW) {
    digitalWrite(ledPin, LOW);

  }


  if (digitalRead(sensorPin)) { // IF Sensor is HIGH we want to send email and close window.
    if (val == HIGH) { // Set the send_flag when the Sensor is activ.
      if (digitalRead(switchPin)); // Window open/closed state.
      if (val == LOW)  // When LOW, the window is open, and we want to set send_flag and close the window.
        Serial.println("Motion detected - Sending email and window is closing...");  //Serial monitor info.
      delay(500);  // Not sure, if delay is  needed.
      send_flag = true;
    }
  }

  if (digitalRead(switchPin)) { // Window open/closed state.
    if (val == HIGH) { // When HIGH, the window is closed, and we do not want to set send_flag while the window is closed.
      send_flag = false;
      Serial.println("STOP switch activated - Window is closed - No need til send email...");  //Serial monitor info.
    }
  }

  if (send_flag) { // the send_flat is set, this means we are or need to start sending SMTP commands
    if (do_next()) { // execute the next command
      count++; // increment the count so that the next command will be executed next time.
    }
  }
}


// do_next executes the SMTP command in the order required.
boolean do_next()
{

  switch (count) {
    case 0:
      Serial.println("Connecting...");
      return wifi.connectTCP(F(HOST), PORT);
      break;
    case 1:
      // send "EHLO ip_address" command. Server will reply with "250" and welcome message
      return wifi.cipSend("EHLO computer.com", F("250")); // ideally an ipaddress should go in place
      // of "computer.com" but I think the email providers
      // check the IP anyways so I just put anything.
      break;
    case 2:
      // send "AUTH LOGIN" command to the server will reply with "334 username" base 64 encoded
      return wifi.cipSend("AUTH LOGIN", F("334 VXNlcm5hbWU6"));
      break;
    case 3:
      // send username/email base 64 encoded, the server will reply with "334 password" base 64 encoded
      return wifi.cipSend(EMAIL_FROM_BASE64, F("334 UGFzc3dvcmQ6"));
      break;
    case 4:
      // send password base 64 encoded, upon successful login the server will reply with 235.
      return wifi.cipSend(EMAIL_PASSWORD_BASE64, F("235"));
      break;
    case 5: {
        // send "MAIL FROM:<emali_from@domain.com>" command
        char mailFrom[50] = "MAIL FROM:<"; // If 50 is not long enough change it, do the same for the array in the other cases
        strcat(mailFrom, EMAIL_FROM);
        strcat(mailFrom, ">");

        return wifi.cipSend(mailFrom, F("250"));
        break;
      }
    case 6: {
        // send "RCPT TO:<email_to@domain.com>" command
        char rcptTo[50] = "RCPT TO:<";
        strcat(rcptTo, EMAIL_TO);
        strcat(rcptTo, ">");
        return wifi.cipSend(rcptTo, F("250"));
        break;
      }
    case 7:
      // Send "DATA"  command, the server will reply with something like "334 end message with \r\n.\r\n."
      return wifi.cipSend("DATA", F("354"));
      break;
    case 8: {
        // apply "FROM: from_name <from_email@domain.com>" header
        char from[100] = "FROM: ";
        strcat(from, EMAIL_FROM);
        strcat(from, " ");
        strcat(from, "<");
        strcat(from, EMAIL_FROM);
        strcat(from, ">");
        return wifi.cipSend(from);
        break;
      }
    case 9: {
        // apply TO header
        char to[100] = "TO: ";
        strcat(to, EMAIL_TO);
        strcat(to, "<");
        strcat(to, EMAIL_TO);
        strcat(to, ">");
        return wifi.cipSend(to);
        break;
      }
    case 10: {
        // apply SUBJECT header
        char subject[50] = "SUBJECT: ";
        strcat(subject, SUBJECT);
        return wifi.cipSend(subject);
        break;
      }
    case 11:
      return wifi.cipSend("\r\n");   // marks end of header (SUBJECT, FROM, TO, etc);
      break;
    case 12:
      return wifi.cipSend(EMAIL_CONTENT);
      break;
    case 13:
      return wifi.cipSend("\r\n.");  // marks end of data command
      break;
    case 14:
      return wifi.cipSend("QUIT");
      break;
    case 15:
      wifi.closeTCP();
      return true;
      break;
    case 16:
      Serial.println("Alarm has been activ");
      send_flag = false;
      count = 0;
      return false; // we don't want to increment the count
      break;
    default:
      break;
  }


}

[/code]

Apparently, you have not looked at the state change detection example. You want to send a message when the motion sensor reports "motion just started", not when "motion is detected".