Хотите, чтобы программа отправляла ОДНО электронное письмо в конце программы со всеми данными - PullRequest
1 голос
/ 04 мая 2019

Итак, у меня есть код, который я сделал, чтобы он проверял погоду для вас и т. Д. У меня есть также, чтобы он отправлял вам электронное письмо (если вы этого хотите) с данными для вашего поиска погоды.

НО, он отправляет только последний выполненный вами поиск, а не все поиски.

Я понятия не имею, как мне поступить, чтобы получить код для сбора всех данных в цикле, а затем отправить электронное письмосо всеми ответами и поисками.Код здесь - это обычный код, который у меня есть, не пытаясь собрать все данные и затем отправить их, я действительно не знаю, как заставить это сделать: 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()

1 Ответ

1 голос
/ 04 мая 2019

Чтобы отправить много предметов, вы должны сохранить их в списке

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()
...