The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feat] Add User invitation emails when inviting users to litellm (#10615)
Ishaan Jaff1fb28c13a1c9
diff --git a/enterprise/enterprise_callbacks/send_emails/base_email.py b/enterprise/enterprise_callbacks/send_emails/base_email.pyindex 1b9b601738a..7cb58c1a4ee 100644--- a/enterprise/enterprise_callbacks/send_emails/base_email.py+++ b/enterprise/enterprise_callbacks/send_emails/base_email.py@@ -9,10 +9,16 @@ from typing import List, Optionalfrom litellm._logging import verbose_proxy_loggerfrom litellm.integrations.custom_logger import CustomLogger+from litellm.integrations.email_templates.email_footer import EMAIL_FOOTERfrom litellm.integrations.email_templates.key_created_email import (KEY_CREATED_EMAIL_TEMPLATE,)+from litellm.integrations.email_templates.user_invitation_email import (+ USER_INVITATION_EMAIL_TEMPLATE,+)+from litellm.proxy._types import WebhookEventfrom litellm.types.enterprise.enterprise_callbacks.send_emails import (+ EmailParams,SendKeyCreatedEmailEvent,)from litellm.types.integrations.slack_alerting import LITELLM_LOGO_URL@@ -22,50 +28,97 @@ class BaseEmailLogger(CustomLogger):DEFAULT_LITELLM_EMAIL = "[email protected]"DEFAULT_SUPPORT_EMAIL = "[email protected]"+ async def send_user_invitation_email(self, event: WebhookEvent):+ """+ Send email to user after inviting them to the team+ """+ email_params = await self._get_email_params(+ user_id=event.user_id, user_email=getattr(event, "user_email", None)+ )+ # Implement invitation email logic using email_params++ verbose_proxy_logger.debug(+ f"send_user_invitation_email_event: {json.dumps(event, indent=4, default=str)}"+ )++ email_html_content = USER_INVITATION_EMAIL_TEMPLATE.format(+ email_logo_url=email_params.logo_url,+ recipient_email=email_params.recipient_email,+ base_url=email_params.base_url,+ email_support_contact=email_params.support_contact,+ email_footer=EMAIL_FOOTER,+ )++ await self.send_email(+ from_email=self.DEFAULT_LITELLM_EMAIL,+ to_email=[email_params.recipient_email],+ subject=f"LiteLLM: {event.event_message}",+ html_body=email_html_content,+ )++ pass+async def send_key_created_email(self, send_key_created_email_event: SendKeyCreatedEmailEvent):"""Send email to user after creating key for the user"""- email_logo_url = os.getenv("EMAIL_LOGO_URL", None) or LITELLM_LOGO_URL- email_support_contact = os.getenv(- "EMAIL_SUPPORT_CONTACT", self.DEFAULT_SUPPORT_EMAIL- )- base_url = os.getenv("PROXY_BASE_URL", "http://0.0.0.0:4000")-- recipient_email: Optional[str] = (- send_key_created_email_event.user_email- or await self._lookup_user_email_from_db(- user_id=send_key_created_email_event.user_id- )+ email_params = await self._get_email_params(+ user_id=send_key_created_email_event.user_id,+ user_email=send_key_created_email_event.user_email,)- if recipient_email is None:- raise ValueError(- f"User email not found for user_id: {send_key_created_email_event.user_id}. User email is required to send email."- )verbose_proxy_logger.debug(f"send_key_created_email_event: {json.dumps(send_key_created_email_event, indent=4, default=str)}")email_html_content = KEY_CREATED_EMAIL_TEMPLATE.format(- email_logo_url=email_logo_url,- recipient_email=recipient_email,+ email_logo_url=email_params.logo_url,+ recipient_email=email_params.recipient_email,key_budget=self._format_key_budget(send_key_created_email_event.max_budget),key_token=send_key_created_email_event.virtual_key,- base_url=base_url,- email_support_contact=email_support_contact,+ base_url=email_params.base_url,+ email_support_contact=email_params.support_contact,+ email_footer=EMAIL_FOOTER,)await self.send_email(from_email=self.DEFAULT_LITELLM_EMAIL,- to_email=[recipient_email],+ to_email=[email_params.recipient_email],subject=f"LiteLLM: {send_key_created_email_event.event_message}",html_body=email_html_content,)pass+ async def _get_email_params(+ self, user_id: Optional[str] = None, user_email: Optional[str] = None+ ) -> EmailParams:+ """+ Get common email parameters used across different email sending methods++ Returns:+ EmailParams object containing logo_url, support_contact, base_url, and recipient_email+ """+ logo_url = os.getenv("EMAIL_LOGO_URL", None) or LITELLM_LOGO_URL+ support_contact = os.getenv("EMAIL_SUPPORT_CONTACT", self.DEFAULT_SUPPORT_EMAIL)+ base_url = os.getenv("PROXY_BASE_URL", "http://0.0.0.0:4000")++ recipient_email: Optional[str] = (+ user_email or await self._lookup_user_email_from_db(user_id=user_id)+ )+ if recipient_email is None:+ raise ValueError(+ f"User email not found for user_id: {user_id}. User email is required to send email."+ )++ return EmailParams(+ logo_url=logo_url,+ support_contact=support_contact,+ base_url=base_url,+ recipient_email=recipient_email,+ )+def _format_key_budget(self, max_budget: Optional[float]) -> str:"""Format the key budget to be displayed in the emaildiff --git a/litellm/integrations/email_templates/email_footer.py b/litellm/integrations/email_templates/email_footer.pynew file mode 100644index 00000000000..feb692354a0--- /dev/null+++ b/litellm/integrations/email_templates/email_footer.py@@ -0,0 +1,10 @@+EMAIL_FOOTER = """+<div class="footer">+ <p>© 2025 LiteLLM. All rights reserved.</p>+ <div class="social-links">+ <a href="https://twitter.com/litellm">Twitter</a> •+ <a href="https://github.com/BerriAI/litellm">GitHub</a> •+ <a href="https://litellm.ai">Website</a>+ </div>+</div>+"""diff --git a/litellm/integrations/email_templates/key_created_email.py b/litellm/integrations/email_templates/key_created_email.pyindex a292223db27..3cf18d827c1 100644--- a/litellm/integrations/email_templates/key_created_email.py+++ b/litellm/integrations/email_templates/key_created_email.py@@ -205,14 +205,7 @@ response = client.chat.completions.create(<br><h2>Need Help?</h2><p>If you have any questions or need assistance, please contact us at {email_support_contact}.</p></div>- <div class="footer">- <p>© 2023 LiteLLM. All rights reserved.</p>- <div class="social-links">- <a href="https://twitter.com/litellm">Twitter</a> •- <a href="https://github.com/BerriAI/litellm">GitHub</a> •- <a href="https://litellm.ai">Website</a>- </div>- </div>+ {email_footer}</div></body></html>diff --git a/litellm/integrations/email_templates/user_invitation_email.py b/litellm/integrations/email_templates/user_invitation_email.pynew file mode 100644index 00000000000..68cda56a92b--- /dev/null+++ b/litellm/integrations/email_templates/user_invitation_email.py@@ -0,0 +1,175 @@+"""+Modern Email Templates for LiteLLM Email Service with professional styling+"""++USER_INVITATION_EMAIL_TEMPLATE = """+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Welcome to LiteLLM</title>+ <style>+ body, html {{+ margin: 0;+ padding: 0;+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;+ color: #333333;+ background-color: #f8f8f8;+ line-height: 1.5;+ }}+ .container {{+ max-width: 560px;+ margin: 20px auto;+ background-color: #ffffff;+ border-radius: 8px;+ overflow: hidden;+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);+ }}+ .logo {{+ padding: 24px 0 0 24px;+ text-align: left;+ }}+ .greeting {{+ font-size: 16px;+ margin-bottom: 20px;+ color: #333333;+ }}+ .content {{+ padding: 24px 40px 32px;+ }}+ h1 {{+ font-size: 24px;+ font-weight: 600;+ margin-top: 24px;+ margin-bottom: 16px;+ color: #333333;+ }}+ p {{+ font-size: 16px;+ color: #333333;+ margin-bottom: 16px;+ line-height: 1.5;+ }}+ .intro-text {{+ margin-bottom: 24px;+ }}+ .link {{+ color: #6366f1;+ text-decoration: none;+ font-weight: 500;+ }}+ .link:hover {{+ text-decoration: underline;+ }}+ .link-with-arrow {{+ display: inline-flex;+ align-items: center;+ color: #6366f1;+ text-decoration: none;+ font-weight: 500;+ margin-bottom: 20px;+ }}+ .link-with-arrow:hover {{+ text-decoration: underline;+ }}+ .arrow {{+ margin-left: 6px;+ }}+ .divider {{+ height: 1px;+ background-color: #f1f1f1;+ margin: 24px 0;+ }}+ .btn {{+ display: inline-block;+ padding: 12px 24px;+ background-color: #5c5ce0;+ color: #ffffff !important;+ text-decoration: none;+ border-radius: 6px;+ font-weight: 500;+ margin-top: 12px;+ text-align: center;+ font-size: 15px;+ transition: background-color 0.2s ease;+ }}+ .btn:hover {{+ background-color: #4b4bb3;+ }}+ .btn-container {{+ text-align: center;+ margin: 24px 0;+ }}+ .footer {{+ padding: 24px 40px 32px;+ text-align: left;+ color: #666;+ font-size: 14px;+ }}+ .quickstart {{+ margin-top: 32px;+ }}+ </style>+</head>+<body>+ <div class="container">+ <div class="logo">+ <img src="{email_logo_url}" alt="LiteLLM Logo" style="height: 32px; width: auto;">+ </div>+ <div class="content">+ <h1>Welcome to LiteLLM</h1>++ <div class="greeting">+ <p>Hi {recipient_email},</p>+ </div>++ <div class="intro-text">+ <p>LiteLLM allows you to call 100+ LLM providers in the OpenAI API format. Get started by accepting your invitation.</p>+ </div>++ <div class="btn-container">+ <a href="{base_url}" class="btn">Accept Invitation</a>+ </div>++ <div class="quickstart">+ <p>Here's a quickstart guide to get you started:</p>+ </div>++ <div class="divider"></div>++ <a href="https://docs.litellm.ai/docs/proxy/user_keys" class="link-with-arrow">+ Make your first LLM request →+ <span class="arrow"></span>+ </a>++ <p>Making LLM requests with OpenAI SDK, Langchain, LlamaIndex, and more.</p>++ <div class="divider"></div>++ <a href="https://docs.litellm.ai/docs/supported_endpoints" class="link-with-arrow">+ Supported Endpoints →+ <span class="arrow"></span>+ </a>++ <p>View all supported LLM endpoints on LiteLLM (/chat/completions, /embeddings, /responses etc.)</p>++ <div class="divider"></div>++ <a href="https://docs.litellm.ai/docs/pass_through/vertex_ai" class="link-with-arrow">+ Passthrough Endpoints →+ <span class="arrow"></span>+ </a>++ <p>We support calling VertexAI, Anthropic, and other providers in their native API format.</p>++ <div class="divider"></div>++ <p>Thanks for signing up. We're here to help you and your team. If you have any questions, contact us at {email_support_contact}</p>++ </div>+ {email_footer}+ </div>+</body>+</html>+"""diff --git a/litellm/proxy/hooks/user_management_event_hooks.py b/litellm/proxy/hooks/user_management_event_hooks.pynew file mode 100644index 00000000000..b56d3143daf--- /dev/null+++ b/litellm/proxy/hooks/user_management_event_hooks.py@@ -0,0 +1,198 @@+"""+Hooks that are triggered when a litellm user event occurs+"""++import asyncio+import uuid+from datetime import datetime, timezone+from typing import Optional++from pydantic import BaseModel++import litellm+from enterprise.enterprise_callbacks.send_emails.base_email import BaseEmailLogger+from litellm._logging import verbose_proxy_logger+from litellm.proxy._types import (+ AUDIT_ACTIONS,+ CommonProxyErrors,+ LiteLLM_AuditLogs,+ Litellm_EntityType,+ LiteLLM_UserTable,+ LitellmTableNames,+ NewUserRequest,+ NewUserResponse,+ UserAPIKeyAuth,+ WebhookEvent,+)+from litellm.proxy.management_helpers.audit_logs import create_audit_log_for_update+++class UserManagementEventHooks:+ @staticmethod+ async def async_user_created_hook(+ data: NewUserRequest,+ response: NewUserResponse,+ user_api_key_dict: UserAPIKeyAuth,+ ):+ """+ This hook is called when a new user is created on litellm++ Handles:+ - Creating an audit log for the user creation+ - Sending a user invitation email to the user+ """+ from litellm.proxy.proxy_server import litellm_proxy_admin_name, prisma_client++ #########################################################+ ########## Send User Invitation Email ################+ #########################################################+ await UserManagementEventHooks.async_send_user_invitation_email(+ data=data,+ response=response,+ user_api_key_dict=user_api_key_dict,+ )++ #########################################################+ ########## CREATE AUDIT LOG ################+ #########################################################+ try:+ if prisma_client is None:+ raise Exception(CommonProxyErrors.db_not_connected_error.value)+ user_row: BaseModel = await prisma_client.db.litellm_usertable.find_first(+ where={"user_id": response.user_id}+ )++ user_row_litellm_typed = LiteLLM_UserTable(+ **user_row.model_dump(exclude_none=True)+ )+ asyncio.create_task(+ UserManagementEventHooks.create_internal_user_audit_log(+ user_id=user_row_litellm_typed.user_id,+ action="created",+ litellm_changed_by=user_api_key_dict.user_id,+ user_api_key_dict=user_api_key_dict,+ litellm_proxy_admin_name=litellm_proxy_admin_name,+ before_value=None,+ after_value=user_row_litellm_typed.model_dump_json(+ exclude_none=True+ ),+ )+ )+ except Exception as e:+ verbose_proxy_logger.warning(+ "Unable to create audit log for user on `/user/new` - {}".format(str(e))+ )+ pass++ @staticmethod+ async def async_send_user_invitation_email(+ data: NewUserRequest,+ response: NewUserResponse,+ user_api_key_dict: UserAPIKeyAuth,+ ):+ """+ Send a user invitation email to the user+ """+ event = WebhookEvent(+ event="internal_user_created",+ event_group=Litellm_EntityType.USER,+ event_message="Welcome to LiteLLM Proxy",+ token=response.token,+ spend=response.spend or 0.0,+ max_budget=response.max_budget,+ user_id=response.user_id,+ user_email=response.user_email,+ team_id=response.team_id,+ key_alias=response.key_alias,+ )++ #########################################################+ ########## V2 USER INVITATION EMAIL ################+ #########################################################+ initialized_email_loggers = (+ litellm.logging_callback_manager.get_custom_loggers_for_type(+ callback_type=BaseEmailLogger+ )+ )+ if len(initialized_email_loggers) > 0:+ for email_logger in initialized_email_loggers:+ if isinstance(email_logger, BaseEmailLogger):+ await email_logger.send_user_invitation_email(+ event=event,+ )++ #########################################################+ ########## LEGACY V1 USER INVITATION EMAIL ################+ #########################################################+ if data.send_invite_email is True:+ await UserManagementEventHooks.send_legacy_v1_user_invitation_email(+ data=data,+ response=response,+ user_api_key_dict=user_api_key_dict,+ event=event,+ )++ @staticmethod+ async def send_legacy_v1_user_invitation_email(+ data: NewUserRequest,+ response: NewUserResponse,+ user_api_key_dict: UserAPIKeyAuth,+ event: WebhookEvent,+ ):+ """+ Send a user invitation email to the user+ """+ from litellm.proxy.proxy_server import general_settings, proxy_logging_obj++ # check if user has setup email alerting+ if "email" not in general_settings.get("alerting", []):+ raise ValueError(+ "Email alerting not setup on config.yaml. Please set `alerting=['email']. \nDocs: https://docs.litellm.ai/docs/proxy/email`"+ )++ # If user configured email alerting - send an Email letting their end-user know the key was created+ asyncio.create_task(+ proxy_logging_obj.slack_alerting_instance.send_key_created_or_user_invited_email(+ webhook_event=event,+ )+ )++ @staticmethod+ async def create_internal_user_audit_log(+ user_id: str,+ action: AUDIT_ACTIONS,+ litellm_changed_by: Optional[str],+ user_api_key_dict: UserAPIKeyAuth,+ litellm_proxy_admin_name: Optional[str],+ before_value: Optional[str] = None,+ after_value: Optional[str] = None,+ ):+ """+ Create an audit log for an internal user.++ Parameters:+ - user_id: str - The id of the user to create the audit log for.+ - action: AUDIT_ACTIONS - The action to create the audit log for.+ - user_row: LiteLLM_UserTable - The user row to create the audit log for.+ - litellm_changed_by: Optional[str] - The user id of the user who is changing the user.+ - user_api_key_dict: UserAPIKeyAuth - The user api key dictionary.+ - litellm_proxy_admin_name: Optional[str] - The name of the proxy admin.+ """+ if not litellm.store_audit_logs:+ return++ await create_audit_log_for_update(+ request_data=LiteLLM_AuditLogs(+ id=str(uuid.uuid4()),+ updated_at=datetime.now(timezone.utc),+ changed_by=litellm_changed_by+ or user_api_key_dict.user_id+ or litellm_proxy_admin_name,+ changed_by_api_key=user_api_key_dict.api_key,+ table_name=LitellmTableNames.USER_TABLE_NAME,+ object_id=user_id,+ action=action,+ updated_values=after_value,+ before_value=before_value,+ )+ )diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.pyindex f579fae25e4..c00d282a810 100644--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py@@ -24,13 +24,13 @@ import litellmfrom litellm._logging import verbose_proxy_loggerfrom litellm.proxy._types import *from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.hooks.user_management_event_hooks import UserManagementEventHooksfrom litellm.proxy.management_endpoints.common_daily_activity import get_daily_activityfrom litellm.proxy.management_endpoints.common_utils import _user_has_admin_viewfrom litellm.proxy.management_endpoints.key_management_endpoints import (generate_key_helper_fn,prepare_metadata_fields,)-from litellm.proxy.management_helpers.audit_logs import create_audit_log_for_updatefrom litellm.proxy.management_helpers.utils import management_endpoint_wrapperfrom litellm.proxy.utils import handle_exception_on_proxyfrom litellm.types.proxy.management_endpoints.common_daily_activity import (@@ -49,46 +49,6 @@ from litellm.types.proxy.management_endpoints.internal_user_endpoints import (router = APIRouter()-async def create_internal_user_audit_log(- user_id: str,- action: AUDIT_ACTIONS,- litellm_changed_by: Optional[str],- user_api_key_dict: UserAPIKeyAuth,- litellm_proxy_admin_name: Optional[str],- before_value: Optional[str] = None,- after_value: Optional[str] = None,-):- """- Create an audit log for an internal user.-- Parameters:- - user_id: str - The id of the user to create the audit log for.- - action: AUDIT_ACTIONS - The action to create the audit log for.- - user_row: LiteLLM_UserTable - The user row to create the audit log for.- - litellm_changed_by: Optional[str] - The user id of the user who is changing the user.- - user_api_key_dict: UserAPIKeyAuth - The user api key dictionary.- - litellm_proxy_admin_name: Optional[str] - The name of the proxy admin.- """- if not litellm.store_audit_logs:- return-- await create_audit_log_for_update(- request_data=LiteLLM_AuditLogs(- id=str(uuid.uuid4()),- updated_at=datetime.now(timezone.utc),- changed_by=litellm_changed_by- or user_api_key_dict.user_id- or litellm_proxy_admin_name,- changed_by_api_key=user_api_key_dict.api_key,- table_name=LitellmTableNames.USER_TABLE_NAME,- object_id=user_id,- action=action,- updated_values=after_value,- before_value=before_value,- )- )--def _update_internal_new_user_params(data_json: dict, data: NewUserRequest) -> dict:if "user_id" in data_json and data_json["user_id"] is None:data_json["user_id"] = str(uuid.uuid4())@@ -222,12 +182,7 @@ async def new_user(```"""try:- from litellm.proxy.proxy_server import (- general_settings,- litellm_proxy_admin_name,- prisma_client,- proxy_logging_obj,- )+ from litellm.proxy.proxy_server import prisma_client# Check for duplicate emailawait _check_duplicate_user_email(data.user_email, prisma_client)@@ -283,62 +238,7 @@ async def new_user(else:raise e- if data.send_invite_email is True:- # check if user has setup email alerting- if "email" not in general_settings.get("alerting", []):- raise ValueError(- "Email alerting not setup on config.yaml. Please set `alerting=['email']. \nDocs: https://docs.litellm.ai/docs/proxy/email`"- )-- event = WebhookEvent(- event="internal_user_created",- event_group=Litellm_EntityType.USER,- event_message="Welcome to LiteLLM Proxy",- token=response.get("token", ""),- spend=response.get("spend", 0.0),- max_budget=response.get("max_budget", 0.0),- user_id=response.get("user_id", None),- user_email=response.get("user_email", None),- team_id=response.get("team_id", "Default Team"),- key_alias=response.get("key_alias", None),- )-- # If user configured email alerting - send an Email letting their end-user know the key was created- asyncio.create_task(- proxy_logging_obj.slack_alerting_instance.send_key_created_or_user_invited_email(- webhook_event=event,- )- )-- try:- if prisma_client is None:- raise Exception(CommonProxyErrors.db_not_connected_error.value)- user_row: BaseModel = await prisma_client.db.litellm_usertable.find_first(- where={"user_id": response["user_id"]}- )-- user_row_litellm_typed = LiteLLM_UserTable(- **user_row.model_dump(exclude_none=True)- )- asyncio.create_task(- create_internal_user_audit_log(- user_id=user_row_litellm_typed.user_id,- action="created",- litellm_changed_by=user_api_key_dict.user_id,- user_api_key_dict=user_api_key_dict,- litellm_proxy_admin_name=litellm_proxy_admin_name,- before_value=None,- after_value=user_row_litellm_typed.model_dump_json(- exclude_none=True- ),- )- )- except Exception as e:- verbose_proxy_logger.warning(- "Unable to create audit log for user on `/user/new` - {}".format(str(e))- )-- return NewUserResponse(+ new_user_response = NewUserResponse(key=response.get("token", ""),expires=response.get("expires", None),max_budget=response["max_budget"],@@ -355,6 +255,22 @@ async def new_user(budget_duration=response.get("budget_duration", None),model_max_budget=response.get("model_max_budget", None),)++ #########################################################+ ########## USER CREATED HOOK ################+ #########################################################+ asyncio.create_task(+ UserManagementEventHooks.async_user_created_hook(+ data=data,+ response=new_user_response,+ user_api_key_dict=user_api_key_dict,+ )+ )+ #########################################################+ ########## END USER CREATED HOOK ################+ #########################################################++ return new_user_responseexcept Exception as e:verbose_proxy_logger.exception("/user/new: Exception occured - {}".format(str(e))@@ -819,7 +735,7 @@ async def user_update(**user_row.model_dump(exclude_none=True))asyncio.create_task(- create_internal_user_audit_log(+ UserManagementEventHooks.create_internal_user_audit_log(user_id=user_row_litellm_typed.user_id,action="updated",litellm_changed_by=user_api_key_dict.user_id,diff --git a/litellm/types/enterprise/enterprise_callbacks/send_emails.py b/litellm/types/enterprise/enterprise_callbacks/send_emails.pyindex 634bb444c4b..5cf9630b183 100644--- a/litellm/types/enterprise/enterprise_callbacks/send_emails.py+++ b/litellm/types/enterprise/enterprise_callbacks/send_emails.py@@ -1,6 +1,15 @@+from pydantic import BaseModel+from litellm.proxy._types import WebhookEvent+class EmailParams(BaseModel):+ logo_url: str+ support_contact: str+ base_url: str+ recipient_email: str++class SendKeyCreatedEmailEvent(WebhookEvent):virtual_key: str"""diff --git a/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py b/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.pyindex ccc596de148..c46912e3a8c 100644--- a/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py+++ b/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py@@ -9,7 +9,7 @@ from fastapi.testclient import TestClientsys.path.insert(0, os.path.abspath("../../.."))from enterprise.enterprise_callbacks.send_emails.base_email import BaseEmailLogger-from litellm.proxy._types import Litellm_EntityType+from litellm.proxy._types import Litellm_EntityType, WebhookEventfrom litellm.types.enterprise.enterprise_callbacks.send_emails import (SendKeyCreatedEmailEvent,)@@ -80,6 +80,100 @@ async def test_send_key_created_email(assert "$100.0" in call_args["html_body"]+async def test_send_user_invitation_email(+ base_email_logger, mock_send_email, mock_lookup_user_email+):+ # Setup test data+ event = WebhookEvent(+ user_id="test_user",+ user_email="[email protected]",+ event_group=Litellm_EntityType.USER,+ event="internal_user_created",+ event_message="User Invitation",+ spend=0.0,+ )++ # Mock environment variables+ with mock.patch.dict(+ os.environ,+ {+ "EMAIL_LOGO_URL": "https://test-logo.com",+ "EMAIL_SUPPORT_CONTACT": "[email protected]",+ "PROXY_BASE_URL": "http://test.com",+ },+ ):+ # Execute+ await base_email_logger.send_user_invitation_email(event)++ # Verify+ mock_send_email.assert_called_once()+ call_args = mock_send_email.call_args[1]+ assert call_args["from_email"] == BaseEmailLogger.DEFAULT_LITELLM_EMAIL+ assert call_args["to_email"] == ["[email protected]"]+ assert call_args["subject"] == "LiteLLM: User Invitation"+ assert "[email protected]" in call_args["html_body"]+++async def test_send_user_invitation_email_from_db(+ base_email_logger, mock_send_email, mock_lookup_user_email+):+ # Setup test data with no direct email but one in the database+ event = WebhookEvent(+ user_id="test_user",+ event_group=Litellm_EntityType.USER,+ event="internal_user_created",+ event_message="User Invitation",+ spend=0.0,+ )++ # Mock the lookup to return an email+ mock_lookup_user_email.return_value = "[email protected]"++ # Mock environment variables+ with mock.patch.dict(+ os.environ,+ {+ "EMAIL_LOGO_URL": "https://test-logo.com",+ "EMAIL_SUPPORT_CONTACT": "[email protected]",+ "PROXY_BASE_URL": "http://test.com",+ },+ ):+ # Execute+ await base_email_logger.send_user_invitation_email(event)++ # Verify+ mock_lookup_user_email.assert_called_once_with(user_id="test_user")+ mock_send_email.assert_called_once()+ call_args = mock_send_email.call_args[1]+ assert call_args["from_email"] == BaseEmailLogger.DEFAULT_LITELLM_EMAIL+ assert call_args["to_email"] == ["[email protected]"]+ assert call_args["subject"] == "LiteLLM: User Invitation"+ assert "[email protected]" in call_args["html_body"]+++async def test_send_user_invitation_email_no_email(+ base_email_logger, mock_lookup_user_email+):+ # Setup test data with no email+ event = WebhookEvent(+ user_id="test_user",+ event_group=Litellm_EntityType.USER,+ event="internal_user_created",+ event_message="User Invitation",+ spend=0.0,+ )++ # Mock lookup to return None+ mock_lookup_user_email.return_value = None++ # Test that it raises ValueError+ with pytest.raises(ValueError, match="User email not found"):+ await base_email_logger.send_user_invitation_email(event)++@pytest.mark.asyncioasync def test_send_key_created_email_no_email(base_email_logger, mock_lookup_user_email