"""
اختبار إرسال إيميل باستخدام sendmail بدلاً من send_message
"""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# SMTP Configuration
SMTP_HOST = "mail.ai4ksa.com"
SMTP_PORT = 465
SMTP_USERNAME = "ithelpdesk@ai4ksa.com"
SMTP_PASSWORD = "ithelpdesk@123"
RECIPIENT_EMAIL = "ashraffarid@gmail.com"

def send_test_email():
    print("=" * 50)
    print("Testing SMTP with sendmail method")
    print("=" * 50)
    print(f"Host: {SMTP_HOST}:{SMTP_PORT}")
    print(f"From: {SMTP_USERNAME}")
    print(f"To: {RECIPIENT_EMAIL}")
    print()
    
    try:
        # Create message
        msg = MIMEMultipart('alternative')
        msg['From'] = f"SmartLife Alert <{SMTP_USERNAME}>"
        msg['To'] = RECIPIENT_EMAIL
        msg['Subject'] = "SmartLife - Test Email (sendmail method)"
        msg['Reply-To'] = SMTP_USERNAME
        
        body = """
        <html>
        <body dir="rtl" style="font-family: Arial, sans-serif;">
            <h2>🎉 تم بنجاح!</h2>
            <p>هذا بريد إلكتروني تجريبي باستخدام طريقة sendmail.</p>
            <p>الوقت: {}</p>
            <hr>
            <p style="color: #666; font-size: 12px;">SmartLife Monitoring System</p>
        </body>
        </html>
        """.format(__import__('datetime').datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        
        msg.attach(MIMEText(body, 'html', 'utf-8'))

        # Connect with SSL
        print("Connecting to SMTP server with SSL...")
        server = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, timeout=30)
        server.set_debuglevel(1)  # Enable debug output
        
        print("\nLogging in...")
        server.login(SMTP_USERNAME, SMTP_PASSWORD)
        
        print("\nSending message using sendmail...")
        # Use sendmail instead of send_message
        server.sendmail(
            from_addr=SMTP_USERNAME,
            to_addrs=[RECIPIENT_EMAIL],
            msg=msg.as_string()
        )
        
        print("\nQuitting...")
        server.quit()
        print("\n✓ Email sent successfully!")
        print(f"Check inbox AND spam folder at: {RECIPIENT_EMAIL}")
        
    except smtplib.SMTPAuthenticationError as e:
        print(f"\n❌ Authentication failed: {e}")
    except smtplib.SMTPRecipientsRefused as e:
        print(f"\n❌ Recipients refused: {e}")
    except smtplib.SMTPDataError as e:
        print(f"\n❌ Data error: {e}")
    except Exception as e:
        print(f"\n❌ Error: {type(e).__name__}: {e}")

if __name__ == "__main__":
    send_test_email()
