因此,我编写了一个代码,使其能够为您检查天气等。 我也有它,因此它会向您发送一封电子邮件(如果需要),其中包含用于天气搜索的数据。
但是,它只会发送您上一次执行的搜索,而不是所有搜索。
我不知道如何获取代码以收集循环中的所有数据,然后向电子邮件发送所有答案和搜索信息。这里的代码只是我的普通代码,没有尝试收集所有数据然后发送它,我真的不知道该怎么做: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()
答案 0 :(得分:1)
要发送许多物品,您必须将其保留在列表中
results = []
while True:
results.append({
'city': city,
'degrees': degrees,
'humidity': humidity
})
然后您可以将其添加到消息中
for item in results:
html_message += """City: {}<br>
Temperature: {:.1f}°C<br>
Humidity: {}%<b>
""".format(item['city'], item['degrees'], item['humidity'])
具有其他更改的完整工作代码
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()