Setting email alert between 108300 and 108500 - python

I am fairly new to Python coding and need some help, I am trying to implement email sending when a scale gets to weights between 10839 and 10850
I know I can use w>10840 and anything above this will trigger an email but the hx711 connected to the pi occasionally spikes causing a false email to be sent so I need it to only send emails when the weight is between 10839 and 10850.
Here is a sample of the code I am using, note I used == but as the pi updates every 5 seconds I have found it can bypass the exact weight without setting off an email. That's why I want to set more of a range
if w==10840:
if flag == 0:
lcdclear()
lcdprint("Fuel Cell Has Been Replenished")
setCursor(0,1);
lcdprint("Sending Email")
server = smtplib.SMTP('mail.jon2.com', 587)
server.starttls()
server.login("jon2#jon2.com", "aaaa1111")
msg = "Fuel Cell Has Been Replenished"
server.sendmail("jon1#jon2.co.uk", msg)
server.quit()

To check if value is between a range you can use this:
if 10839 < w < 10850:
if flag == 0:
lcdclear()
lcdprint("Fuel Cell Has Been Replenished")
setCursor(0,1);
lcdprint("Sending Email")
server = smtplib.SMTP('mail.jon2.com', 587)
server.starttls()
server.login("jon2#jon2.com", "aaaa1111")
msg = "Fuel Cell Has Been Replenished"
server.sendmail("jon1#jon2.co.uk", msg)
server.quit()

Related

How to tell program to sleep for 60 seconds after 50 actions have been completed (emails sent) in python

I have this code that sends out emails individually through gmail from a list of emails in an excel file. I just want to know how to make the bot pause for 60 seconds after it's sent 50 emails and then continue with the list after the 60 seconds is up. I'm just trying to be safe with gmails daily limits.
import smtplib
import openpyxl as xl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username = str(input('Your Username:' ))
password = str(input('Your Password:' ))
From = username
Subject = 'Free Beats and Samples For You :)'
wb = xl.load_workbook(r'C:\Users\19548\Documents\EMAILS.xlsx')
sheet1 = wb.get_sheet_by_name('EMAIL TEST - Sheet1')
names = []
emails = []
for cell in sheet1['A']:
emails.append(cell.value)
for cell in sheet1['B']:
names.append(cell.value)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(username, password)
for i in range(len(emails)):
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = emails[i]
msg['Subject'] = Subject
text = '''
{}
'''.format(names[i])
msg.attach(MIMEText(text, 'plain'))
message = msg.as_string()
server.sendmail(username, emails[i], message)
print('Mail sent to', emails[i])
server.quit()
print('All emails sent successfully!')
You can use time.sleep() to wait a given number of seconds, and you can keep track of the number of emails sent using a variable that gets incremented with each iteration of the loop. Since you're already working with both the emails themselves and their indices, you can simplify this counting by using Python's enumerate function, which gives you both the next value and its corresponding index:
for index, email in enumerate(emails, start=1):
msg = <...>
message = msg.as_string()
server.sendmail(username, email, message)
if index % 50 == 0:
time.sleep(60)
if(your_value%50==0):
time.sleep(60)

Send mail every so often

I am trying to send an email every so often from python. My situation is the next:
I have a database that receives sensor values ​​such as temperature, humidity, pressure, etc. So the database is updated every so often, in my case data is sent every 1 minute to the database, what I try to do is that when the temperature passes a certain value, for example 26 ° C, sending mail stops for example 10 or 20 minutes and send another one in case the temperature stays above 26. I managed to send the mail, but my situation is that it does not stop and sends mails without stopping while the value of the temperature is above 26 ° C.
This is the code:
dataSQL = []
sql_conn = MySQLdb.connect('localhost', 'root', 'pass', 'DB')
cursor = sql_conn.cursor()
cursor.execute("SELECT value,timestamp FROM sensorParser where sensor='TC'")
rows = cursor.fetchall()
for row in rows:
dataSQL.append(list(row))
labels = ['value','timestamp']
df = pd.DataFrame.from_records(dataSQL, columns=labels)
X = df['timestamp']
Y = df['value'].astype(float)
if (float(df['value'][0]) > 26):
email = 'email1#gmail.com'
password = 'pass'
send_to_email = 'email2#gmail.com'
subject = 'ALERTA!!!! SENSORES'
message = 'Los valores de las variables criticas han superado el limite'
file_location = 'C:\\Users\\User\\Desktop\\prograpython\\image.jpg'
msg = MIMEMultipart()
msg['From'] = email
msg['To'] = send_to_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
filename = os.path.basename(file_location)
attachment = open(file_location, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to_email, text)
server.quit()
Regards.
You can import time into the program and save the time value when the email is sent. Then you can add a check wether ten minutes have passed since the time was saved into the if-statement like this:
import time
timestamp = 0
# ... your code
if (float(df['value'][0]) > 26) and (timestamp == 0 or time.time() - timestamp > 600):
timestamp = time.time()
# ... your code
time.time() outputs the so-called unix time, which is the number of seconds that have passed since the 1st of January 1970. In the new expression for the if-statement you also check wether more than 600 seconds have passed since you last called the code in the statement, you can change the number of seconds to fit your needs.
Feel free to ask if any further questions should arise.
PS: Please limit the code you share to what is necessary, it makes the question more friendly-looking and easier to read :)

mail-client issue in Python

My script should take the user inputs and login to the server but when I give it the inputs it false and I tried different servers and different emails and the passwords are correct. How can I determine what's wrong?
import smtplib
sent = 'true'
ss = 'true'
repeat = 1
while sent == 'true':
m_email = input ('Enter Your Email Address: ')
m_server = input ('Entere Your Email Server: ')
m_auth = input ('username?\n')
p_auth = input ('password?\n')
r_email = input ('enter the reciver email: ')
subject = input ('enter Your Subject: ')
subject = 'subject '+ subject
m_massege = input ('Your Massege: ')
massege = subject + '\n \n' + m_massege
while ss == 'true' or repeat == "5" :
try:
server = smtplib.SMTP(m_server)
server.ehlo()
server.starttls()
server.login(m_auth,p_auth)
server.Sendmail(m_email,r_mail,massege)
print ("Mail Sent Successfully!")
sent = 'false'
except:
print ('sending failed')
repeat =+ 1
exit()
I've also had issues with smtplib and what I found was that it was not actually a code issue but rather an issue with the email account. For example, in my case I was trying to log into my yahoo mail account to automate emails and it kept failing so I had to go to my yahoo account security settings and enable "allow unsecured application login".
Point is: the problem isn't with your code but with the security settings on the email accounts (For me neither gmail nor yahoo worked).

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

python emailing one line at a time

My email program is emailing each line of the message as a separate email, i would like to know how to send all of the message in one email, when the email is sent the program will return to the beginning.
import smtplib
from email.mime.text import MIMEText
a = 1
while a == 1:
print " "
To = raw_input("To: ")
subject = raw_input("subject: ")
input_list = []
print "message: "
while True:
input_str = raw_input(">")
if input_str == "." and input_list[-1] == "":
break
else:
input_list.append(input_str)
for line in input_list:
# Create a MIME text message and populate its values
msg = MIMEText(line)
msg['Subject'] = subject
msg['From'] = '123#example.com'
msg['To'] = To
server = smtplib.SMTP_SSL('server', 465)
server.ehlo()
server.set_debuglevel(1)
server.ehlo()
server.login('username', 'password')
# Send a properly formatted MIME message, rather than a raw string
server.sendmail('user#example.net', To, msg.as_string())
server.close()
(the part that takes multiple lines was made with the help Paul Griffiths, Multiline user input python)
for line in input_list:
# Create a MIME text message and populate its values
msg = MIMEText(line)
You are calling server.sendmail in this loop.
Build your entire msg first (in a loop), THEN add all of your headers and send your message.

Categories

Resources