0% found this document useful (0 votes)
6 views5 pages

PayBill Management System Code

The PayBill Management System is a Python application that allows users to manage their bills, including viewing, paying, and receiving receipts via email. It features a login system for users and admins, with functionalities for admins to manage users and bills. The application uses MySQL for database management and generates PDF receipts for payments, which are sent via email using SMTP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views5 pages

PayBill Management System Code

The PayBill Management System is a Python application that allows users to manage their bills, including viewing, paying, and receiving receipts via email. It features a login system for users and admins, with functionalities for admins to manage users and bills. The application uses MySQL for database management and generates PDF receipts for payments, which are sent via email using SMTP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PayBill Management System - Code

import [Link]
from getpass import getpass
from fpdf import FPDF
import smtplib
from [Link] import MIMEText
from [Link] import MIMEMultipart
from [Link] import MIMEBase
from email import encoders
import os

# Database connection
def connect_db():
return [Link](
host="localhost",
user="root", # Replace with your MySQL username
password="", # Replace with your MySQL password
database="PayBillDB"
)

# Email Sending Function


def send_email(to_email, pdf_path, bill_id):
sender_email = "youremail@[Link]" # Replace with your email
sender_password = "yourpassword" # Replace with your app password

subject = f"Billing Receipt for Bill ID: {bill_id}"


body = "Dear User,\n\nPlease find attached the billing receipt for your recent payment. Thank you for using
our service!"

# Email setup
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = to_email
msg['Subject'] = subject
[Link](MIMEText(body, 'plain'))

# Attach PDF
with open(pdf_path, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload([Link]())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename={[Link](pdf_path)}")
[Link](part)

# Sending email
try:
server = [Link]('[Link]', 587)
[Link]()
[Link](sender_email, sender_password)
[Link](sender_email, to_email, msg.as_string())
print(f"Receipt emailed successfully to {to_email}")
except Exception as e:
print(f"Failed to send email: {e}")
finally:
[Link]()

# Generate PDF for the bill


def generate_bill_pdf(bill, pdf_path):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
[Link](200, 10, txt="Payment Receipt", ln=True, align='C')
[Link](200, 10, txt=f"Bill ID: {bill['id']}", ln=True)
[Link](200, 10, txt=f"Amount: {bill['amount']}", ln=True)
[Link](200, 10, txt=f"Due Date: {bill['due_date']}", ln=True)
[Link](200, 10, txt=f"Status: Paid", ln=True)
[Link](pdf_path)
print(f"Receipt PDF generated: {pdf_path}")

# Login system
def login():
username = input("Enter username: ")
password = getpass("Enter password: ")

try:
conn = connect_db()
cursor = [Link](dictionary=True)
[Link]("SELECT * FROM users WHERE username = %s AND password = MD5(%s)", (username, password))
user = [Link]()

if user:
print(f"Login successful! Welcome, {user['role']}.")
if user['role'] == 'Admin':
admin_dashboard()
elif user['role'] == 'User':
user_dashboard(user['id'])
else:
guest_dashboard()
else:
print("Invalid username or password!")
except [Link] as err:
print(f"Error: {err}")
finally:
if conn.is_connected():
[Link]()

# Admin dashboard
def admin_dashboard():
print("\n---- Admin Dashboard ----")
print("1. View all users")
print("2. View all bills")
print("3. Add a new bill")
print("4. Logout")
choice = input("Enter your choice: ")
if choice == '1':
view_users()
elif choice == '2':
view_bills()
elif choice == '3':
add_bill()
elif choice == '4':
print("Logging out...")
else:
print("Invalid choice!")
admin_dashboard()

# View all users (Admin only)


def view_users():
try:
conn = connect_db()
cursor = [Link]()
[Link]("SELECT id, username, email, role FROM users")
users = [Link]()
print("\n---- User List ----")
for user in users:
print(user)
except [Link] as err:
print(f"Error: {err}")
finally:
if conn.is_connected():
[Link]()
admin_dashboard()

# View all bills (Admin only)


def view_bills():
try:
conn = connect_db()
cursor = [Link]()
[Link]("SELECT * FROM bills")
bills = [Link]()
print("\n---- Bill List ----")
for bill in bills:
print(bill)
except [Link] as err:
print(f"Error: {err}")
finally:
if conn.is_connected():
[Link]()
admin_dashboard()

# Add a new bill (Admin only)


def add_bill():
user_id = input("Enter user ID: ")
amount = input("Enter bill amount: ")
due_date = input("Enter due date (YYYY-MM-DD): ")

try:
conn = connect_db()
cursor = [Link]()
[Link]("INSERT INTO bills (user_id, amount, due_date) VALUES (%s, %s, %s)", (user_id, amount,
due_date))
[Link]()
print("Bill added successfully!")
except [Link] as err:
print(f"Error: {err}")
finally:
if conn.is_connected():
[Link]()
admin_dashboard()

# User dashboard with email feature


def user_dashboard(user_id):
print("\n---- User Dashboard ----")
print("1. View my bills")
print("2. Pay a bill and receive receipt")
print("3. Logout")
choice = input("Enter your choice: ")

if choice == '1':
view_my_bills(user_id)
elif choice == '2':
pay_bill_and_email(user_id)
elif choice == '3':
print("Logging out...")
else:
print("Invalid choice!")
user_dashboard(user_id)

# View bills for the logged-in user


def view_my_bills(user_id):
try:
conn = connect_db()
cursor = [Link]()
[Link]("SELECT * FROM bills WHERE user_id = %s", (user_id,))
bills = [Link]()
print("\n---- My Bills ----")
for bill in bills:
print(bill)
except [Link] as err:
print(f"Error: {err}")
finally:
if conn.is_connected():
[Link]()
user_dashboard(user_id)

# Pay a bill and send receipt via email


def pay_bill_and_email(user_id):
bill_id = input("Enter bill ID to pay: ")
try:
conn = connect_db()
cursor = [Link](dictionary=True)
# Check if the bill exists and is unpaid
[Link]("SELECT * FROM bills WHERE id = %s AND user_id = %s AND status = 'Pending'", (bill_id,
user_id))
bill = [Link]()

if bill:
# Update bill status to 'Paid'
[Link]("UPDATE bills SET status = 'Paid' WHERE id = %s", (bill_id,))
[Link]()

# Get user's email


[Link]("SELECT email FROM users WHERE id = %s", (user_id,))
user = [Link]()
email = user['email']

# Generate PDF receipt


pdf_path = f"bill_receipt_{bill_id}.pdf"
generate_bill_pdf(bill, pdf_path)

# Send receipt via email


send_email(email, pdf_path, bill_id)
else:
print("Bill not found or already paid!")
except [Link] as err:
print(f"Error: {err}")
finally:
if conn.is_connected():
[Link]()
user_dashboard(user_id)

# Guest dashboard
def guest_dashboard():
print("\n---- Guest Dashboard ----")
print("Welcome! You have limited access.")
print("Returning to login...")
login()

# Main function
if __name__ == "__main__":
print("Welcome to PayBill Management System!")
login()

You might also like