import os from django.conf import settings from django.core.mail import send_mail from django.template.loader import render_to_string from django.urls import reverse import uuid def send_verification_email(user, request, is_parent=False): """ Sends a verification email to a new user (player or parent). """ # Ensure user has a verification code if not user.verification_code: user.verification_code = uuid.uuid4() user.save() # Build the verification URL verification_path = reverse('verify_account', kwargs={'verification_code': str(user.verification_code)}) verification_url = request.build_absolute_uri(verification_path) # Determine which template and subject to use if is_parent: subject = 'Verifizieren Sie Ihr Eltern-Konto für den Baseball Organisator' template_prefix = 'accounts/email/parent_verification' else: subject = 'Willkommen beim Baseball Organisator! Bitte verifizieren Sie Ihr Konto.' template_prefix = 'accounts/email/player_verification' context = { 'user': user, 'verification_url': verification_url, 'verification_code': user.verification_code } # Render email body from templates email_body_txt = render_to_string(f'{template_prefix}.txt', context) email_body_html = render_to_string(f'{template_prefix}.html', context) # Send or simulate email based on settings if settings.MTP_EMAIL_SEND == 1: send_mail( subject=subject, message=email_body_txt, from_email=settings.DEFAULT_FROM_EMAIL, # Make sure this is set in settings.py recipient_list=[user.email], html_message=email_body_html, fail_silently=False, ) else: # Simulate email by saving to a file mbox_content = f"""From: {settings.DEFAULT_FROM_EMAIL} To: {user.email} Subject: {subject} MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="boundary" --boundary Content-Type: text/plain; charset="utf-8" {email_body_txt} --boundary Content-Type: text/html; charset="utf-8" {email_body_html} --boundary-- """ # Ensure the tmp_mails directory exists os.makedirs('tmp_mails', exist_ok=True) # Save the email to a file file_path = os.path.join('tmp_mails', f'{user.email}_{user.verification_code}.mbox') with open(file_path, 'w') as f: f.write(mbox_content)