Using a while loop only once - python

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

Related

Room Temperature Alarm to Email - Raspberry Pi

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?

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)

Script to check a page

I have a script that alerts me by mail when a phrase changes on a web page. I tried many things, but I can't fix the isAvailable() function: the script says "not available" every time, whether or not I give it an available server. Have you any clues?
# CONFIG
TARGET_KIMSUFI_ID = "160sk1" # something like 160sk1
TARGET_DESCR = ""
EMAIL_FROM_ADDRS = ""
EMAIL_TO_ADRS = ""
EMAIL_SMTP_LOGIN = EMAIL_FROM_ADDRS
EMAIL_SMTP_PASSWD = ""
EMAIL_SMTP_SERVER = ""
# CODE
import urllib.request
import smtplib
import time
def isAvailable():
rawPageContent = urllib.request.urlopen("https://www.kimsufi.com/en/servers.xml").read()
rawPageContent = str(rawPageContent)
poz = rawPageContent.find(TARGET_KIMSUFI_ID)
row = rawPageContent[poz:]
poz = row.find("</tr>")
row = row[:poz]
searchText = "Currently being replenished"
poz = row.find(searchText)
return poz != -1
def sendEmailWithMessageAvailable():
msg = "From: KIMSUFI HUNTER <"+EMAIL_FROM_ADDRS+">\r\n"+\
"To: "+EMAIL_TO_ADRS+"\r\n"+\
"Subject: [KIMSUFI] "+TARGET_DESCR+" is now AVAILABLE!\r\n"+\
"\r\n"+\
"kimsufi-hunter.py has detected that "+TARGET_DESCR+" is now ["+time.ctime()+"] available!\r\n"+\
"https://www.kimsufi.com/en/\r\n"
server = smtplib.SMTP(EMAIL_SMTP_SERVER)
server.starttls()
server.login(EMAIL_SMTP_LOGIN,EMAIL_SMTP_PASSWD)
server.sendmail(EMAIL_FROM_ADDRS, EMAIL_TO_ADRS, msg)
server.quit()
while True:
if isAvailable():
print(time.ctime() + " -- KIMSUFI "+TARGET_DESCR+" not available")
nextSleep = 5 #5secs
else:
print(time.ctime() + " -- KIMSUFI "+TARGET_DESCR+" AVAILABLE!!! -- sleeping for 5 minutes")
sendEmailWithMessageAvailable()
nextSleep = 5*60 #5mins
time.sleep(nextSleep)
Your isAvailable() function returns True if the website is available, False otherwise. You should change the if statement to:
if not isAvailable():
...

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

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