import uuid
import random
import string
import re
from bs4 import BeautifulSoup
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string


def send_html_email(template, subject, from_email, to_emails, context, text_template=None):
    """
    Sends an HTML email to the specified recipients.
    :param subject: The subject of the email.
    :param from_email: The sender email address.
    :param to_emails: The list of recipient email addresses.
    :param html_template: The template containing the HTML content of the email.
    :param text_template: Optional. The template containing the text content of the email.If None, the text version of the email will be automatically generated from the HTML version.
    :param context: Optional. The context data to be passed to the email templates.
    :return: True if the email was sent successfully, False otherwise.
    """
    try:
        # Render the HTML template with the context data
        html_content = render_to_string(template, context)

        # If a text template is provided, render it with the context data
        if text_template is not None:
            text_content = render_to_string(text_template, context)
        else:
            # Otherwise, generate the text version from the HTML version using BeautifulSoup
            soup = BeautifulSoup(html_content, 'html.parser')
            text_content = soup.get_text()

        # Create the email message
        msg = EmailMultiAlternatives(
            subject=subject,
            body=text_content,
            from_email=from_email,
            to=to_emails
        )

        # Attach the HTML content as an alternative content type
        msg.attach_alternative(html_content, "text/html")

        # Send the email
        msg.send()

        return True  # Email sent successfully
    except Exception as e:
        # Log the exception or handle it as needed
        print(f"Error sending email: {e}")
        return False  # Email sending failed
