py_stepik/delivery_with_email_send.py
2024-01-26 16:54:41 +03:00

101 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import smtplib
def send_email(from_addr, to_addr, subject, text, encode="utf-8"):
passwd = "**********"
server = "smtp.yandex.ru"
port = 587
charset = f"Content-Type: text/plain; charset={encode}"
mime = "MIME-Version: 1.0"
body = "\r\n".join(
(
f"From: {from_addr}",
f"To: {to_addr}",
f"Subject: {subject}",
mime,
charset,
"",
text,
)
)
try:
smtp = smtplib.SMTP(server, port)
smtp.starttls()
smtp.ehlo()
smtp.login(from_addr, passwd)
smtp.sendmail(from_addr, to_addr, body.encode(encode))
except smtplib.SMTPException as err:
print("Что - то пошло не так...")
raise err
finally:
smtp.quit()
goods = {
"пицца": 250,
"роллы": 300,
"чипсы": 100,
"чай": 50,
}
menu = [*zip(range(1, len(goods) + 1), *zip(*goods.items()))]
selection = {i: name for i, name, *_ in menu}
cart = {}
def show_menu():
print("Меню:")
for i, name, price in menu:
print(f"{i} - {name} {price} руб.")
print(f"{menu[-1][0] + 1} - выход\n")
def show_cart():
print("Ваша корзина:")
total = 0
for name, count in cart.items():
pos_sum = goods[name] * count
print(f"{name} - {count} шт. - {pos_sum} руб.")
total += pos_sum
print(" - - - - - - ")
print(f"Итого: {total} руб.\n")
def ask_user():
show_menu()
i = int(input("Ваш выбор: "))
while not 0 < i <= len(menu) + 1:
show_menu()
i = int(input("Ваш выбор: "))
if i <= len(menu):
return selection[i]
def get_order_text():
s = f"Адрес клиента: {input('Введите Ваш адрес: ')}\n"
s += "Заказ клиента:\n"
total = 0
for name, count in cart.items():
pos_sum = goods[name] * count
s += f"{name} - {count} шт. - {pos_sum} руб.\n"
total += pos_sum
s += " - - - - - - \n"
s += f"Итого: {total} руб."
return s
print("Добро пожаловать в сервис заказа еды")
for name in iter(ask_user, None):
cart.setdefault(name, 0)
cart[name] += 1
print()
show_cart()
if len(cart) > 0:
from_addr = "my_app@yandex.ru"
to_addr = "super_courier@gmail.com"
subject = "Заказ от клиента"
text = get_order_text()
send_email(from_addr, to_addr, subject, text)