Room Temperature Alarm to Email - Raspberry Pi - python

I'm trying to send and email based on High temperature or humidity but i cant figure out how to add this. Its my first time using DHT22 with Raspberry Pi so not sure how to structure my code.
I've tried a variety of codes others have suggested but they either no longer work on Python 3 (originally Python 2 - depreciated), or the code I've written just doesn't do anything except monitor and log with no email on high temp.
My original coding so far is this:
import os
import time
from time import sleep
from datetime import datetime
import Adafruit_DHT
file = open("/home/pi/TempHumLog.csv", "a")
if os.stat("/home/pi/TempHumLog.csv").st_size == 0:
file.write("Date,Time,Temperature,Humidity\n")
while True:
DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4
temperature, humidity = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
file.write("{0},{1},{3:0.2f}*C,{2:0.2f}%rh\n".format(time.strftime("%d/%m/%y"), time.strftime("%H:%M:%S"), temperature, humidity))
file.flush()
print("{0},{1},{3:0.2f}*C,{2:0.2f}%rh\n".format(time.strftime("%d/%m/%y"), time.strftime("%H:%M:%S"), temperature, humidity))
time.sleep(5)
import smtplib
#Email Variables
SMTP_SERVER = 'smtp.gmail.com' #Email Server (don't change!)
SMTP_PORT = 587 #Server Port (don't change!)
GMAIL_USERNAME = 'example#gmail.com' #change this to match your gmail account
GMAIL_PASSWORD = 'example pw' #change this to match your gmail password
class Emailer:
def sendmail(self, recipient, subject, content):
#Create Headers
headers = ["From: " + GMAIL_USERNAME, "Subject: " + subject, "To: " + recipient,
"MIME-Version: 1.0", "Content-Type: text/html"]
headers = "\r\n".join(headers)
#Connect to Gmail Server
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo()
#Login to Gmail
session.login(GMAIL_USERNAME, GMAIL_PASSWORD)
#Send Email & Exit
session.sendmail(GMAIL_USERNAME, recipient, headers + "\r\n\r\n" + content)
session.quit
sender = Emailer()
while True:
if temperature > 24:
sendTo = 'example#gmail.com'
emailSubject = "High Temp!"
emailContent = "<br>A High Temp has Activated At: " + time.ctime() + "<br><br>Check The Room Temperature Levels"
sender.sendmail(sendTo, emailSubject, emailContent)
print("Email Sent")
elif temperature < 23:
sendTo = 'example#gmail.com'
emailSubject = "Room Temp Healthy"
emailContent = "High Room Temp Alarm Has Cleared At: " + time.ctime()
sender.sendmail(sendTo, emailSubject, emailContent)
print("Email Sent")
time.sleep(5)
At this time, no errors come through the terminal but it doesn't send any email. I've tried adding something like this:
instance = dht22.DHT22(pin=4)
while True:
result = instance.read()
tempHI = 26
tempLOW = 19
if (result.temperature) > tempHI:
**Send Email Script**
But no luck!
Any ideas how i can get the high temperature to trigger the email?

Related

Cannot connect to imap server on python

I'm a networking student who has little programming experience and I have simple project on my hands where I need to make a simple notification that notifies the user when an email arrives in gmail. I have been trying to get this to work for the last few weeks and I am honestly stuck and struggling. I'm using the code below and I think the problem is the authentication bit, where I can't connect to the server. All help is appreciated.
import imaplib
import re
import time
import subprocess
## enter your account details bellow!
imapServer = "imap.gmail.com"
port = "993"
username = "example#gmail.com"
password = "password"
##how often to check ? give interval in seconds! Checking too often might performance and stability.
checkInterval = 120
Mailbox = imaplib.IMAP4_SSL(imapServer, port)
rc,resp = Mailbox.login(username,password)
if rc == 'OK':
print("Connected to mail-server " + imapServer)
rc, message = Mailbox.status('INBOX', "(UNSEEN)")
unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
oldValue = 0
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
file.write(str(unreadCount))
file.close
while(1):
rc, message = Mailbox.status('INBOX', "(UNSEEN)")
unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
oldValue = int(file.readline())
file.close()
if (unreadCount>oldValue):
subprocess.call(["notify-send", "-u", "low", "low", "t", "5000", "New email!", "New email!",
"You have " + str(unreadCount) + " unread " + "emails!" if unreadCount > 1 else "email!",
"--icon=email"])
if oldValue != unreadCount:
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
file.write(str(unreadCount))
file.close()
time.sleep(checkInterval)
else :
print('Fail to connect')
Mailbox.logout()
file.remove()

Potential workarounds for gmail blocking?

So I have a CSV file that contains about 1000 emails, names, companies, etc. Once I deploy my program, it reaches about 80 emails and then I am assuming Google is blocking me from requesting to reach its server again.
I am thinking that I set a timer, for every 70 emails, delete each in the dataframe, wait a few minutes, and redeploy starting from where it left off, because of the deleted rows. Do you think this would work? If so, how would I build a little timer like this? I can create a tracker, but how to initialize a rerun of the program?
Are there any other potential workarounds? Does it have to do with my code constantly resigning in to Google?
import smtplib
import pandas as pd
class Gmail(object):
def __init__(self, email, password, recepient):
self.email = email
self.password = password
self.recepient = recepient
self.server = 'smtp.gmail.com'
self.port = 465
session = smtplib.SMTP_SSL(self.server, self.port)
session.ehlo
session.login(self.email, self.password)
self.session = session
print('Connected to Gmail account successfully.')
def send_message(self, subject, body):
headers = [
"From: " + self.email,
"Subject: " + subject,
"To: " + self.recepient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
self.session.sendmail(
self.email,
self.recepient,
headers + "\r\n\r\n" + body)
print('- Message has been sent.')
df = pd.read_csv('export.csv', error_bad_lines=False)
for index, row in df.iterrows():
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
comp_name = (row['Account Name'])
print('Email to: ' + comp_name)
per_name = (row['Primary Contact: Full Name'])
print('Email to: ' + per_name)
rec = (row['Primary Contact Email'])
print('Email to: ' + rec)
message_body = 'Hi'
gm = Gmail('email#gmail.com', 'password', rec)
gm.send_message('test', message_body)
print('-- Message for ' + rec + ' (' + comp_name + ') is completed.')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
print('*********************************')
print('Finish reading through CSV.')
print('*********************************')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
Any thoughts would be really helpful.
Thank you!

Using a while loop only once

I am working on a simple program to email me the weather in my city each morning. At the moment, it works, but only once. Using a while loop works, but since I have it set to,
while time == 0600:
send my mail etc
Now obviously, that makes it so for the entirety of that minute, I get spammed with mail. So I need to figure out a way for something to happen once, every 24 hours.
Here is my full code (currently only working once, until I restart it).
import smtplib, pywapi, datetime
weather = True
loopmsg = True
loopmsg1 = True
def send():
loopmsg = True
loopmsg1 = True
global weather
while weather == True:
if loopmsg == True:
print('Initial Loop Initiated')
loopmsg = False
time = datetime.datetime.now()
time = str(time)
time = time[11:]
time = time[:-10]
time = time.replace(":", "")
time = int(time)
fromaddr = 'xxx'
toaddrs = 'xxx'
while time == 0600:
print('Time is correct')
weather_com_result = pywapi.get_weather_from_weather_com('ASXX0075')
msg = "It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "°C in Your City."
msg = msg.encode('utf-8')
# Credentials (if needed)
username = 'xxx'
password = 'xxx'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print('Sent')
#weather = False
#while weather == False:
# if loopmsg1 == True:
# print('Second Loop Initiated')
# loopmsg1 = False
# while time > 0600:
# send()
send()
First of all, you're running a script all day long for it to do something only once a day. This is illogical. You should schedule a task on your OS (Win, Linux, Mac - they all have a way to schedule tasks) so that your script is activated at 6h every day; and remove the time condition inside your script.
If you want to get fancy, create a Telegram bot and have it send you a message any time you want, on your phone, for the location you specify right then.
The script however is easy to fix. You're using that while loop as an if. Just add a variable that will make it send an e-mail only once.
if time == 0500:
send_email = True
if send_email and time == 0600:
print('Time is correct')
send_email = False
weather_com_result = pywapi.get_weather_from_weather_com('ASXX0075')
....
Why not just have a break statement right after you send the email? This just causes you to break out of the loop. Then it will execute the rest of the program.
while time == 0600:
print('Time is correct')
weather_com_result = pywapi.get_weather_from_weather_com('ASXX0075')
msg = "It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "°C in Your City."
msg = msg.encode('utf-8')
# Credentials (if needed)
username = 'xxx'
password = 'xxx'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print('Sent')
break

sending emails in a loop In PYTHON 2.7

I am currently trying to make a program that send multiple emails to my self in a loop. I have already written 2 patches of code but i can not seem to get them to work. (I am running this on a raspberry pi so exsuse any weird directorys).
This is my first patch of while loop code
import os
i = 0
while i < 2:
os.pause(4)
os.system("home/Tyler/desktop/test.py")
i += 1
This opens the email "sending" part /\ .
This down here is the "sending" part /
import smtplib
smtpUser = 'smilingexample#gmail.com'
smtpPass = 'password'
toAdd = 'Example#aim.com'
fromAdd = smtpUser
subject = 'yep'
header = 'to: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
body = 'hi'
print header + '\n' + body
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtpUser, smtpPass)
s.sendmail(fromAdd, toAdd, header + '\n\n' + body)
s.quit ()
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email import Charset
Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
maillist = []
def send_email(messages_list, smtpUser=None, smtpPass=None, tls=False):
failed = []
try:
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
if tls:
s.starttls()
s.ehlo()
if smtpUser and smtpPass:
s.login(smtpUser, smtpPass)
except:
print "ehlo failed"
failed = [x[0] for x in messages_list]
else:
for to_address,from_address,subject,encoding,mesg in messages_list:
try:
if len(mesg) == 2:
msg = MIMEMultipart('alternative')
else:
msg = MIMEText(mesg[0],'plain','utf-8')
msg['Subject'] = "%s" % Header(subject, 'utf-8')
if len(from_address) == 2:
msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[-1])
else:
msg['From'] = from_address[-1]
if len(to_address) == 2:
msg['From'] = "\"%s\" <%s>" % (Header(to_address[0], 'utf-8'), to_address[-1])
else:
msg['To'] = to_address[-1]
msg.set_charset("utf-8")
if len(mesg) == 2:
part1 = MIMEText(mesg[0], 'plain','utf-8')
part2 = MIMEText(mesg[1], 'html','utf-8')
msg.attach(part1)
msg.attach(part2)
s.sendmail(from_address[-1], to_address[-1], msg.as_string())
except:
traceback.print_exc()
failed.append(to_address[-1])
try:
s.quit()
except:
pass
return failed
maillist.append(( ['someone#gmail.com'],["Me","noreply#example.com"],'Subject','utf-8',['text_message','html but you can delete this list element'] ))
for k in send_email(maillist, smtpUser='you#gmail.com', smtpPass='pwd', tls=True):
print k, 'not delivered'
Here's what we use to send alternative Mime messages with alternative body. It is not necessary though so you can send simple text messages as well.
It's prepared to send from localhost but you can easily modify it to use it properly.

error sending multiple mails through smtp

I am trying to develop a small python application that allows it's user to send multiple mails through python, I am using gmail, I have allowed Access for less secure apps, it doesn't send.
I have searched stackoverflow for similar problems, but it seemed that most of the used codes are completely different in implementation, even after trying many of hem, they all through exception
import smtplib
from telnetlib import Telnet
def addSenders(message):
num = input("enter number of recievers : ")
num = int (num)
i = 0
emailList = []
while i < num :
nameStr = input("enter name")
mailStr = input("enter e-mail")
emailList.append(mailStr)
if i == 0:
message += nameStr + " <" + mailStr + ">"
print(message)
else:
message += "," + nameStr + " <" + mailStr + ">"
i = i + 1
return emailList, message
sender = 'xxxx#gmail.com'
password = "xxxx"
message = """From: xxxx xxxx <xxxxx#gmail.com>
To: To """
to, message = addSenders(message)
message += """
MIME-Version: 1.0
Content-type: text/html
Subject: Any Subject!
<h1> Good Morning :D <h1>
"""
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login(sender, password)
try:
server.sendmail(sender, [to], message)
print ("Successfully sent email")
except:
print ("Error: unable to send email")
server.quit()
output : Error: unable to send email

Categories

Resources