from discord.ext import commands
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from dotenv import load_dotenv
from os import getenv
import html
from datetime import datetime
load_dotenv()
def build_feedback_html(feedback_rows: list[dict[str, str]]) -> str:
feedback_items = []
for i, row in enumerate(feedback_rows, 1):
content = html.escape(row["CONTENT"])
user = html.escape(row["USER"])
timestamp = html.escape(row["TIMESTAMP"])
feedback_items.append(
f"""
"""
)
return f"""
User Feedback Report
User Feedback Report
New feedback submissions
Total feedback submissions: {len(feedback_rows)}
{''.join(feedback_items)}
Generated automatically by PyBot • {datetime.now().strftime('%Y-%m-%d %H:%M')}
Do not reply to this automated message
"""
class Mail(commands.Cog):
def __init__(self, client:commands.Bot):
self.client = client
from utils.sql_commands import DatabaseManager
self.db = DatabaseManager()
@commands.is_owner()
@commands.command(name="mail_feedback")
async def mail(self, ctx:commands.Context[commands.Bot]):
password = getenv("EMAILPASS")
username = getenv("EMAILUSER")
server = getenv("EMAILSERVER")
port = getenv("EMAILPORT")
receiver = getenv("FEEDBACKRECEIVER")
if None in [password, username, server, port, receiver]:
await ctx.reply(
"Email configuration is missing. Please check your environment variables.",
delete_after=5,
)
return
try:
port = int(port)
with smtplib.SMTP(host=server, port=port) as s:
s.starttls()
s.login(username, password)
msg = MIMEMultipart("alternative")
msg["To"] = receiver
msg["From"] = username
msg["Subject"] = "Py feedback"
feedback_rows: list[dict[str, str]] = self.db.fetch_all("SELECT * FROM feedback")
text = build_feedback_html(feedback_rows)
msg.attach(MIMEText(text, "html"))
s.send_message(msg)
await ctx.reply("Mail sent.", delete_after=2)
except Exception as e:
await ctx.reply(f"Failed to send mail: {e}", delete_after=5)
async def setup(client:commands.Bot):
await client.add_cog(Mail(client))