This script sends the user's shopping list to the recipient's email address. Maybe you can help me correct some mistakes.

import smtplib

from email.message import EmailMessage

from getpass import getpass

from collections import defaultdict

import sys

def get_user_input(message, type=str):
    while True:
            return type(input(message))
        except ValueError:
            print(f"Please input a {type}.")

class ShoppingList:

    def __init__(self):
        self.items = defaultdict(int)

    def __str__(self):
        return ("\n".join(f"{product} x {quantity}"
                for product, quantity in self.items.items()))

    def add_item(self, product, quantity):
        self.items[product] += quantity

    def email_to(self, from_email, password, *recipients):
        email = EmailMessage()
        email['Subject'] = "Shopping List"
        email['From'] = from_email
        email['To'] = recipients
        message = str(self)

            s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
            s.login(from_email, password)
            print("\nThe email has been sent.")
        except Exception as e:
            print("\nAn error occurred:", e)

if __name__ == '__main__':
    name = input("Input your name: ")
    print (f"Hi, {name}!")
    shopping_list = ShoppingList()
    while True:
            product = get_user_input("Input the product name (input \"stop\" when you are done): ")
            if product == "stop":
            quantity = get_user_input("Input the product quantity: ", int)              
            shopping_list.add_item(product, quantity)
        except Exception as e:
            print("\nAn error occurred:", e)
    print("\nThese products have been added to the shopping list:")

    email = input("\nEmail: ")
    password = getpass("Password: ")
    recipient = input("Recipient's email: ")
    shopping_list.email_to(email, password, recipient)

    print("\nHave a nice day!")

  • 2
    \$\begingroup\$ It'd help if you could provide a list of changes from your previous version? \$\endgroup\$ – hjpotter92 Feb 24 at 19:12
  • 3
    \$\begingroup\$ What mistakes have you got? \$\endgroup\$ – Yu Zhang Feb 24 at 23:09
  • \$\begingroup\$ what is your problem? \$\endgroup\$ – Benyamin Jafari Feb 25 at 6:09
  • \$\begingroup\$ @hjpotter92 The script now uses functions and a class. Also, instead of asking how many products the user want, I made a loop that keeps asking for product name and it's quantity until the user inputs "stop". \$\endgroup\$ – David Andrei Feb 25 at 10:26
  • \$\begingroup\$ @YuZhang The script works fine. I was asking if you can identify any code mistake I did (about the style etc.). \$\endgroup\$ – David Andrei Feb 25 at 10:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.