Reputation: 87
So I have a code I made that makes it so it checks the weather for you etc. I have it also so it sends you an email (if you want it to) with the data for your weather search.
BUT, it only sends the last search you did, not all the searches.
I have no idea how I would go about getting the code to gather all the data within the loop and THEN send the email with all answers and searches. The code here is just the normal code I have, not with a try for it to gather all data and then send it, I really dont know how I would make it do that :p
# - Good Morning Program -
#Import
import datetime
import requests
import sys
import smtplib
import ad_pw
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#Input
name_of_user = input("What is your name?: ")
#Email
sender_email = ad_pw.email_address
password = ad_pw.email_password
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(sender_email, password)
#Loop
while True:
#Input
city = input('City Name: ')
# API
api_address='http://api.openweathermap.org/data/2.5/weather?appid=0c42f7f6b53b244c78a418f4f181282a&q='
url = api_address + city
json_data = requests.get(url).json()
# Variables
format_add = json_data['main']['temp']
day_of_month = str(datetime.date.today().strftime("%d "))
month = datetime.date.today().strftime("%b ")
year = str(datetime.date.today().strftime("%Y "))
time = str(datetime.datetime.now().strftime("%H:%M:%S"))
degrees = format_add - 273.15
humidity = json_data['main']['humidity']
latitude = json_data['coord']['lon']
longitude = json_data['coord']['lat']
#Program
if degrees < 20 and time > str(12.00):
print("\nGood afternoon " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a mild " + "{:.1f}".format(degrees) +
"°C, you might need a jacket.")
elif degrees < 20 and time < str(12.00):
print("\nGood morning " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a mild " + "{:.1f}".format(degrees) +
"°C, you might need a jacket.")
elif degrees >= 20 and time > str(12.00):
print("\nGood afternoon " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a warm " + "{:.1f}".format(degrees) +
"°C, don't forget to drink water.")
elif degrees >= 20 and time < str(12.00):
print("\nGood morning " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a warm " + "{:.1f}".format(degrees) +
"°C, don't forget to drink water.")
restart = input('Would you like to check another city (y/n)?: ')
if restart == 'y':
continue
else:
# HTML
html_message = """\
<html>
<head></head>
<body>
<p>Hi, """ + str(name_of_user) + """<br>
Here is the data from your weather search:<br>
<br>
City: """ + str(city) + """<br>
Temperature: """ + "{:.1f}".format(degrees) + """°C<br>
Humidity: """ + str(humidity) + """%<b>
</p>
</body>
</html>
"""
# Email
msg = MIMEMultipart('alternative')
msg = MIMEText(html_message, "html")
receive_email = input("Do you want to receive a copy from you search (y/n)?: ")
if receive_email == 'y':
receiver_email = input("Your e-mail: ")
msg['From'] = sender_email
msg['To'] = receiver_email
print(
'Goodbye, an email has been sent to ' + receiver_email + " and you will receive a copy for data from your searched cities there")
server.sendmail(sender_email, receiver_email, msg.as_string())
sys.exit()
else:
print('Goodbye')
sys.exit()
Upvotes: 1
Views: 66
Reputation: 142814
To send many items you have to keep them on list
results = []
while True:
results.append({
'city': city,
'degrees': degrees,
'humidity': humidity
})
And then you can add it to message
for item in results:
html_message += """City: {}<br>
Temperature: {:.1f}°C<br>
Humidity: {}%<b>
""".format(item['city'], item['degrees'], item['humidity'])
Full working code with other changes
import datetime
import requests
import sys
import smtplib
import ad_pw
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail(name_of_user, receiver_email, results):
# HTML
html_message = """\
<html>
<head></head>
<body>
<p>Hi, {}<br>
Here is the data from your weather search:<br>
<br>
""".format(name_of_user)
#---
for item in results:
html_message += """City: {}<br>
Temperature: {:.1f}°C<br>
Humidity: {}%<b>
""".format(item['city'], item['degrees'], item['humidity'])
#---
html_message += "</p>\n</body>\n</html>"
#---
print(html_message)
# Email
msg = MIMEMultipart('alternative')
msg = MIMEText(html_message, "html")
sender_email = ad_pw.email_address
msg['From'] = sender_email
msg['To'] = receiver_email
#Email
password = ad_pw.email_password
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg.as_string())
def display(text_1='afternoon', text_2='you might need a jacket'):
print("\nGood {} {}.".format(text_1, name_of_user))
print("\nThe date today is: {}".format(date))
print("The current time is: {}".format(time))
print("The humidity is: {}%".format(humidity))
print("Latitude and longitude for {} is {},{}".format(city, latitude, longitude))
print("The temperature is a mild {:.1f}°C, {}.".format(degrees, text_2))
# --- main ---
#Input
name_of_user = input("What is your name?: ")
results = []
#Loop
while True:
#Input
city = input('City Name: ')
# API
api_address='http://api.openweathermap.org/data/2.5/weather?appid=0c42f7f6b53b244c78a418f4f181282a&q='
url = api_address + city
json_data = requests.get(url).json()
# Variables
format_add = json_data['main']['temp']
date = str(datetime.date.today().strftime("%d %b %Y"))
time = str(datetime.datetime.now().strftime("%H:%M:%S"))
degrees = format_add - 273.15
humidity = json_data['main']['humidity']
latitude = json_data['coord']['lon']
longitude = json_data['coord']['lat']
results.append({
'city': city,
'degrees': degrees,
'humidity': humidity
})
#Program
if time > '12.00':
text_1 = 'afternoon'
else:
text_1 = 'morning'
if degrees < 20:
text_2 = 'you might need a jacket'
else:
text_2 = "don't forget to drink water."
display(text_1, text_2)
restart = input('Would you like to check another city (y/n)?: ')
if restart.lower().strip() != 'y':
receive_email = input("Do you want to receive a copy from you search (y/n)?: ")
if receive_email.lower().strip() == 'y':
receiver_email = input("Your e-mail: ")
send_mail(name_of_user, receiver_email, results)
print('Goodbye, an email has been sent to {}\
and you will receive a copy for data from your searched cities there'.format(receiver_email))
else:
print('Goodbye')
sys.exit()
Upvotes: 1