# your_app/email_utils.py from flask import current_app import sib_api_v3_sdk from sib_api_v3_sdk.rest import ApiException from .general_utils import backfill_orders def send_order_confirmation_email(order, user): """ Constructs and sends order confirmation emails to the customer and a notification to the client/admin using the Brevo API. Args: order (dict): The complete order document, including 'populated_items'. user (dict): The user document, containing 'email' and 'company_name'. """ # Setup Brevo API client from Flask app config configuration = sib_api_v3_sdk.Configuration() configuration.api_key['api-key'] = current_app.config['BREVO_API_KEY'] api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration)) # --- Common variables for emails --- sender_email = current_app.config['SENDER_EMAIL'] sender_name = "Matax Express" # You can customize this client_admin_email = current_app.config['CLIENT_ADMIN_EMAIL'] customer_email = user['email'] contact_person = user['contactPerson'] order_id_str = str(order['serial_no']) # --- Common portal footer --- portal_footer = """
Remember, you can place new orders, view your order history, manage your cart, and even use our AI-powered quick order feature at our customer portal:
https://matax-express.vercel.app/
Product | Quantity |
---|---|
{item['name']} | {item['quantity']} {item['mode']} |
We have successfully received your order #{order_id_str}. Here are the details:
Delivery Date: {order['delivery_date']}
Delivery Address: {order['delivery_address']}
Contact Number: {order['mobile_number']}
Additional Info: {order.get('additional_info') or 'N/A'}
Thank you for your business!
{portal_footer} """ send_smtp_email_customer = sib_api_v3_sdk.SendSmtpEmail( to=[{"email": customer_email, "name": contact_person}], sender={"email": sender_email, "name": sender_name}, subject=customer_subject, html_content=customer_html_content ) # --- 2. Prepare Email for the Client/Admin --- client_subject = f"New Order Received - #{order_id_str} from {contact_person}" client_html_content = f"""A new order #{order_id_str} has been placed by {contact_person}.
Company: {contact_person}
Email: {customer_email}
Delivery Date: {order['delivery_date']}
Delivery Address: {order['delivery_address']}
Contact Number: {order['mobile_number']}
Additional Info: {order.get('additional_info') or 'N/A'}
Total Amount: ${order.get('total_amount', 0):.2f}
This order has also been sent for PO creation in Xero.
""" send_smtp_email_client = sib_api_v3_sdk.SendSmtpEmail( to=[{"email": client_admin_email}], sender={"email": sender_email, "name": sender_name}, subject=client_subject, html_content=client_html_content ) # --- 3. Send both emails --- api_instance.send_transac_email(send_smtp_email_customer) current_app.logger.info(f"Order confirmation sent to {customer_email} for order {order_id_str}") api_instance.send_transac_email(send_smtp_email_client) current_app.logger.info(f"New order notification sent to {client_admin_email} for order {order_id_str}") # +++ START: NEW EMAIL FUNCTIONS +++ def send_registration_email(user_data): """Sends a welcome/application pending email upon registration.""" configuration = sib_api_v3_sdk.Configuration() configuration.api_key['api-key'] = current_app.config['BREVO_API_KEY'] api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration)) sender_email = current_app.config['SENDER_EMAIL'] sender_name = "Matax Express" recipient_email = user_data['email'] recipient_name = user_data.get('contactPerson', user_data.get('businessName', 'New User')) # --- Common portal footer --- portal_footer = f"""
Once your account is approved, you can place orders, view your order history, manage your cart, and use our AI-powered quick order feature at our customer portal:
https://matax-express.vercel.app/
Thank you for registering. Your application is currently under review by our team.
We will notify you via email as soon as your account is approved.
Thank you for your patience.
Best regards,
The Matax Express Team
tag to preserve formatting in HTML email html_content = f"""New Client Application Received
A new client has submitted an application for an account. Please review the details below and approve them in the admin panel if applicable.
{history_details}""" send_smtp_email = sib_api_v3_sdk.SendSmtpEmail( to=[{ "email": admin_email }], sender={ "email": sender_email, "name": sender_name }, subject=subject, html_content=html_content ) try: api_instance.send_transac_email(send_smtp_email) current_app.logger.info(f"Admin notification for new registration '{registration_data.get('email')}' sent to {admin_email}") except ApiException as e: current_app.logger.error(f"Failed to send admin notification email for registration '{registration_data.get('email')}': {e}") def send_login_notification_email(user): """Sends a notification email upon successful login.""" configuration = sib_api_v3_sdk.Configuration() configuration.api_key['api-key'] = current_app.config['BREVO_API_KEY'] api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration)) sender_email = current_app.config['SENDER_EMAIL'] sender_name = "Matax Express" recipient_email = user['email'] recipient_name = user.get('contactPerson', user.get('company_name', 'Valued Customer')) # --- Common portal footer --- portal_footer = """You can place new orders, view your order history, manage your cart, and even use our AI-powered quick order feature at our customer portal:
""" subject = "New login.." html_content = f"""
https://matax-express.vercel.app/Security Alert: New Login
Hello {recipient_name},
We detected a new login to your Matax Express account just now.
If this was you, you can safely disregard this email. If you do not recognize this activity, please change your password immediately and contact our support team.
Thank you for helping us keep your account secure.
Best regards,
{portal_footer} """ send_smtp_email = sib_api_v3_sdk.SendSmtpEmail( to=[{ "email": recipient_email, "name": recipient_name }], sender={ "email": sender_email, "name": sender_name }, subject=subject, html_content=html_content ) try: api_instance.send_transac_email(send_smtp_email) current_app.logger.info(f"Login notification sent to {recipient_email}") except ApiException as e: current_app.logger.error(f"Failed to send login notification to {recipient_email}: {e}") def send_cart_reminder_email(user, populated_items): """Sends a reminder for items left in the cart.""" configuration = sib_api_v3_sdk.Configuration() configuration.api_key['api-key'] = current_app.config['BREVO_API_KEY'] api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration)) sender_email = current_app.config['SENDER_EMAIL'] sender_name = "Matax Express" recipient_email = user['email'] recipient_name = user.get('contactPerson', user.get('company_name', 'Valued Customer')) # --- Common portal footer --- portal_footer = """
The Matax Express TeamTo complete your order, or to place new ones, please visit our customer portal:
""" subject = "Your items are waiting for you!" items_html = "
https://matax-express.vercel.app/
Product | Quantity |
---|---|
{item['product']['name']} | {item['quantity']} |
Your baby fruits are waiting to arrive! You have some delicious items waiting in your cart.
Ready to complete your order? Please log in to your account to view your cart.
These items are popular and might not be available for long!
Best regards,
The Matax Express Team