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 class Mail(commands.Cog): def __init__(self, client:commands.Bot): self.client = client load_dotenv() 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) # type: ignore # Error invalid as for problem is taken care of above s = smtplib.SMTP(host=server, port=port) # type: ignore s.starttls() s.login(username, password) # type: ignore msg = MIMEMultipart("alternative") msg["To"] = receiver # type: ignore msg["From"] = username # type: ignore msg["Subject"] = "Py feedback" # Fetch feedback from the database feedback_rows:list[dict[str,str]] = self.db.fetch_all("SELECT * FROM feedback") all_feedback = "" for i, row in enumerate(feedback_rows, 1): content = html.escape(row["CONTENT"]) user = html.escape(row["USER"]) timestamp = html.escape(row["TIMESTAMP"]) all_feedback += f"""
  • {i}

    {user}

    {timestamp}

    {content}

  • """ text = f""" User Feedback Report

    User Feedback Report

    New feedback submissions

    Total feedback submissions: {len(feedback_rows)}

    Generated automatically by PyBot • {datetime.now().strftime('%Y-%m-%d %H:%M')}

    Do not reply to this automated message

    """ msg.attach(MIMEText(text, "html")) s.send_message(msg) await ctx.reply("Mail sent.", delete_after=2) s.quit() 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))