Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: add SMTP email service (#15144)

Saurya Velagapudi94f82ede8b31
diff --git a/AGENTS.md b/AGENTS.md
index a0f0320880..e3f7950c28 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -129,6 +129,8 @@ Backend:
- All tests are in `tests/unit/test_*.py`
- To test new code, run `poetry run pytest tests/unit/test_xxx.py` where `xxx` is the appropriate file for the current functionality
- Write all tests with pytest
+ - Enterprise unit tests live under `enterprise/tests`; run them with `PYTHONPATH=enterprise poetry run pytest enterprise/tests/unit/test_xxx.py`
+
Frontend:
- Located in the `frontend` directory
@@ -177,6 +179,9 @@ The `enterprise/` directory contains additional functionality that extends the o
- Authentication and user management (Keycloak integration)
- Database migrations (Alembic)
- Integration services (GitHub, GitLab, Jira, Linear, Slack)
+- Email services: Resend remains in `enterprise/server/services/email_service.py`; SMTPEmailService lives in
+ `enterprise/server/services/smtp_email_service.py` and is used for org invitations/budget alerts plus
+ the SMTP-driven UI email-enabled checks (SMTP_HOST).
- Billing and subscription management (Stripe)
- Telemetry and analytics (PostHog, custom metrics framework)
diff --git a/enterprise/README.md b/enterprise/README.md
index 497ae9a7be..c9e6d2a0bd 100644
--- a/enterprise/README.md
+++ b/enterprise/README.md
@@ -46,6 +46,23 @@ The github service is responsible for interacting with Github APIs. As a consequ
NOTE: in the future we will simply replace the `GithubTokenManager` with keycloak. The `SaaSGithubService` should interact with keycloack instead.
+### Email delivery (SMTP)
+
+Budget alert emails and other SMTP-backed notifications are sent via SMTP when configured.
+If `SMTP_HOST` is unset, email delivery is disabled and the UI can surface manual links
+instead of attempting to send mail.
+
+| Env var | Purpose | Default |
+| --- | --- | --- |
+| `SMTP_HOST` | SMTP server hostname | (required) |
+| `SMTP_PORT` | SMTP server port | `587` |
+| `SMTP_USERNAME` | SMTP auth username | empty |
+| `SMTP_PASSWORD` | SMTP auth password | empty |
+| `SMTP_FROM_EMAIL` | Sender address | `OpenHands <[email protected]>` |
+| `SMTP_USE_SSL` | Use implicit TLS/SSL | `false` |
+| `SMTP_USE_TLS` | StartTLS upgrade (ignored if SSL) | `true` |
+
+
# Areas that are BRITTLE!
## User ID vs User Token
diff --git a/enterprise/server/services/smtp_email_service.py b/enterprise/server/services/smtp_email_service.py
new file mode 100644
index 0000000000..97c5a62eb6
--- /dev/null
+++ b/enterprise/server/services/smtp_email_service.py
@@ -0,0 +1,227 @@
+"""Email service for sending transactional emails via SMTP."""
+
+import os
+import smtplib
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+from typing import TypedDict
+
+from openhands.app_server.utils.logger import openhands_logger as logger
+
+DEFAULT_FROM_EMAIL = 'OpenHands <[email protected]>'
+DEFAULT_WEB_HOST = 'https://app.all-hands.dev'
+
+
+class SMTPSettings(TypedDict):
+ host: str
+ port: int
+ use_ssl: bool
+ use_tls: bool
+ username: str
+ password: str
+ from_email: str
+
+
+class SMTPEmailService:
+ """Service for sending transactional emails via SMTP."""
+
+ @staticmethod
+ def _get_smtp_settings() -> SMTPSettings | None:
+ host = os.environ.get('SMTP_HOST')
+ if not host:
+ return None
+
+ port_value = os.environ.get('SMTP_PORT', '587')
+ try:
+ port = int(port_value)
+ except ValueError:
+ logger.warning(
+ 'SMTP_PORT invalid, defaulting to 587',
+ extra={'smtp_port': port_value},
+ )
+ port = 587
+
+ use_ssl = os.environ.get('SMTP_USE_SSL', 'false').lower() in (
+ 'true',
+ '1',
+ )
+ use_tls = (
+ os.environ.get('SMTP_USE_TLS', 'true').lower() in ('true', '1')
+ and not use_ssl
+ )
+
+ return {
+ 'host': host,
+ 'port': port,
+ 'use_ssl': use_ssl,
+ 'use_tls': use_tls,
+ 'username': os.environ.get('SMTP_USERNAME', ''),
+ 'password': os.environ.get('SMTP_PASSWORD', ''),
+ 'from_email': os.environ.get('SMTP_FROM_EMAIL', DEFAULT_FROM_EMAIL),
+ }
+
+ @staticmethod
+ def _send_smtp_email(
+ to_emails: list[str],
+ subject: str,
+ html: str,
+ extra: dict[str, object] | None = None,
+ ) -> bool:
+ settings = SMTPEmailService._get_smtp_settings()
+ if not settings:
+ logger.warning('SMTP not configured, skipping email')
+ return False
+
+ message = MIMEMultipart('alternative')
+ message['Subject'] = subject
+ message['From'] = str(settings['from_email'])
+ message['To'] = ', '.join(to_emails)
+ message.attach(MIMEText(html, 'html'))
+
+ extra_payload = extra or {}
+
+ try:
+ smtp_class = smtplib.SMTP_SSL if settings['use_ssl'] else smtplib.SMTP
+ client = smtp_class(settings['host'], settings['port'])
+ try:
+ if settings['use_tls']:
+ client.starttls()
+ if settings['username']:
+ client.login(settings['username'], settings['password'])
+ client.sendmail(
+ settings['from_email'],
+ to_emails,
+ message.as_string(),
+ )
+ finally:
+ client.quit()
+ return True
+ except Exception as exc:
+ logger.error(
+ 'Failed to send SMTP email',
+ extra={'error': str(exc), **extra_payload},
+ )
+ return False
+
+ @staticmethod
+ def is_configured() -> bool:
+ """Whether transactional email delivery is configured.
+
+ Returns True when SMTP settings are available so callers can surface
+ "email is not configured" to users instead of letting invitations fail
+ silently.
+ """
+ return SMTPEmailService._get_smtp_settings() is not None
+
+ @staticmethod
+ def build_invitation_url(invitation_token: str) -> str:
+ """Build the absolute acceptance URL for an invitation token.
+
+ WEB_HOST may be configured as a bare hostname (the OHE chart sets it
+ that way), so normalize to an https URL before composing the link.
+ """
+ web_host = os.environ.get('WEB_HOST', DEFAULT_WEB_HOST).strip().rstrip('/')
+ if not web_host:
+ web_host = DEFAULT_WEB_HOST
+ if not web_host.startswith(('http://', 'https://')):
+ web_host = f'https://{web_host}'
+ return (
+ f'{web_host}/api/organizations/members/invite/accept'
+ f'?token={invitation_token}'
+ )
+
+ @staticmethod
+ def send_invitation_email(
+ to_email: str,
+ org_name: str,
+ inviter_name: str,
+ role_name: str,
+ invitation_token: str,
+ invitation_id: int,
+ ) -> None:
+ """Send an organization invitation email.
+
+ Args:
+ to_email: Recipient's email address
+ org_name: Name of the organization
+ inviter_name: Display name of the person who sent the invite
+ role_name: Role being offered (e.g., 'member', 'admin')
+ invitation_token: The secure invitation token
+ invitation_id: The invitation ID for logging
+ """
+ invitation_url = SMTPEmailService.build_invitation_url(invitation_token)
+ subject = f"You're invited to join {org_name} on OpenHands"
+ body = f"""
+ <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
+ <p>Hi,</p>
+
+ <p><strong>{inviter_name}</strong> has invited you to join <strong>{org_name}</strong> on OpenHands as a <strong>{role_name}</strong>.</p>
+
+ <p>Click the button below to accept the invitation:</p>
+
+ <p style="margin: 30px 0;">
+ <a href="{invitation_url}"
+ style="background-color: #c9b974; color: #0D0F11; padding: 8px 16px;
+ text-decoration: none; border-radius: 8px; display: inline-block;
+ font-size: 14px; font-weight: 600;">
+ Accept Invitation
+ </a>
+ </p>
+
+ <p style="color: #666; font-size: 14px;">
+ Or copy and paste this link into your browser:<br>
+ <a href="{invitation_url}" style="color: #c9b974; font-weight: 600;">{invitation_url}</a>
+ </p>
+
+ <p style="color: #666; font-size: 14px;">
+ This invitation will expire in 7 days.
+ </p>
+
+ <p style="color: #666; font-size: 14px;">
+ If you weren't expecting this invitation, you can safely ignore this email.
+ </p>
+
+ <hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">
+
+ <p style="color: #999; font-size: 12px;">
+ Best,<br>
+ The OpenHands Team
+ </p>
+ </div>
+ """
+
+ extra = {'invitation_id': invitation_id, 'email': to_email}
+
+ if SMTPEmailService._send_smtp_email([to_email], subject, body, extra):
+ logger.info('Invitation email sent', extra=extra)
+
+ @staticmethod
+ def send_budget_alert_email(
+ to_emails: list[str],
+ org_name: str,
+ percentage: float,
+ current_spend: float,
+ monthly_limit: float,
+ threshold: int,
+ ) -> None:
+ subject = (
+ f'OpenHands budget alert: {org_name} reached {threshold}% of its limit'
+ )
+ body = f"""
+ <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
+ <p>Hi,</p>
+ <p><strong>{org_name}</strong> has reached <strong>{percentage:.1f}%</strong>
+ of its monthly budget.</p>
+ <p><strong>Current spend:</strong> ${current_spend:,.2f}<br />
+ <strong>Monthly limit:</strong> ${monthly_limit:,.2f}<br />
+ <strong>Threshold:</strong> {threshold}%</p>
+ <p>Please review your Usage & Monitoring dashboard for more details.</p>
+ <hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">
+ <p style="color: #999; font-size: 12px;">Best,<br>The OpenHands Team</p>
+ </div>
+ """
+
+ extra = {'org_name': org_name, 'recipient_count': len(to_emails)}
+
+ if SMTPEmailService._send_smtp_email(to_emails, subject, body, extra):
+ logger.info('Budget alert email sent via SMTP', extra=extra)
diff --git a/enterprise/tests/unit/test_smtp_email_service.py b/enterprise/tests/unit/test_smtp_email_service.py
new file mode 100644
index 0000000000..0f7ec9e872
--- /dev/null
+++ b/enterprise/tests/unit/test_smtp_email_service.py
@@ -0,0 +1,220 @@
+"""Tests for SMTP email service."""
+
+import os
+from unittest.mock import MagicMock, patch
+
+from server.services.smtp_email_service import (
+ DEFAULT_WEB_HOST,
+ SMTPEmailService,
+)
+
+
+class TestSMTPEmailServiceInvitationUrl:
+ """Test cases for invitation URL generation."""
+
+ def test_invitation_url_uses_correct_endpoint(self):
+ """Test that invitation URL points to the correct API endpoint."""
+ smtp_client = MagicMock()
+
+ with (
+ patch.dict(os.environ, {'SMTP_HOST': 'smtp.example.com'}, clear=True),
+ patch(
+ 'server.services.smtp_email_service.smtplib.SMTP',
+ return_value=smtp_client,
+ ),
+ ):
+ SMTPEmailService.send_invitation_email(
+ to_email='[email protected]',
+ org_name='Test Org',
+ inviter_name='Inviter',
+ role_name='member',
+ invitation_token='inv-test-token-12345',
+ invitation_id=1,
+ )
+
+ message = smtp_client.sendmail.call_args[0][2]
+ assert '/api/organizations/members/invite/accept?token=' in message
+ assert 'inv-test-token-12345' in message
+
+ def test_invitation_url_uses_web_host_env_var(self):
+ """Test that invitation URL uses WEB_HOST environment variable."""
+ custom_host = 'https://custom.example.com'
+ smtp_client = MagicMock()
+
+ with (
+ patch.dict(
+ os.environ,
+ {'SMTP_HOST': 'smtp.example.com', 'WEB_HOST': custom_host},
+ clear=True,
+ ),
+ patch(
+ 'server.services.smtp_email_service.smtplib.SMTP',
+ return_value=smtp_client,
+ ),
+ ):
+ SMTPEmailService.send_invitation_email(
+ to_email='[email protected]',
+ org_name='Test Org',
+ inviter_name='Inviter',
+ role_name='member',
+ invitation_token='inv-test-token-12345',
+ invitation_id=1,
+ )
+
+ message = smtp_client.sendmail.call_args[0][2]
+ expected_url = f'{custom_host}/api/organizations/members/invite/accept?token=inv-test-token-12345'
+ assert expected_url in message
+
+ def test_invitation_url_uses_default_host_when_env_not_set(self):
+ """Test that invitation URL falls back to DEFAULT_WEB_HOST when env not set."""
+ smtp_client = MagicMock()
+
+ with (
+ patch.dict(os.environ, {'SMTP_HOST': 'smtp.example.com'}, clear=True),
+ patch(
+ 'server.services.smtp_email_service.smtplib.SMTP',
+ return_value=smtp_client,
+ ),
+ ):
+ SMTPEmailService.send_invitation_email(
+ to_email='[email protected]',
+ org_name='Test Org',
+ inviter_name='Inviter',
+ role_name='member',
+ invitation_token='inv-test-token-12345',
+ invitation_id=1,
+ )
+
+ message = smtp_client.sendmail.call_args[0][2]
+ expected_url = f'{DEFAULT_WEB_HOST}/api/organizations/members/invite/accept?token=inv-test-token-12345'
+ assert expected_url in message
+
+
+class TestSMTPEmailServiceSendInvitationEmail:
+ """Test cases for send_invitation_email method."""
+
+ def test_send_invitation_email_skips_when_smtp_not_configured(self):
+ """Test that email sending is skipped when SMTP is not configured."""
+ with patch.object(
+ SMTPEmailService, '_send_smtp_email', return_value=False
+ ) as mock_send:
+ SMTPEmailService.send_invitation_email(
+ to_email='[email protected]',
+ org_name='Test Org',
+ inviter_name='Inviter',
+ role_name='member',
+ invitation_token='inv-test-token',
+ invitation_id=1,
+ )
+
+ mock_send.assert_called_once()
+
+ def test_send_invitation_email_includes_all_required_info(self):
+ """Test that invitation email includes org name, inviter name, and role."""
+ smtp_client = MagicMock()
+
+ with (
+ patch.dict(
+ os.environ,
+ {
+ 'SMTP_HOST': 'smtp.example.com',
+ 'SMTP_FROM_EMAIL': '[email protected]',
+ },
+ clear=True,
+ ),
+ patch(
+ 'server.services.smtp_email_service.smtplib.SMTP',
+ return_value=smtp_client,
+ ),
+ ):
+ SMTPEmailService.send_invitation_email(
+ to_email='[email protected]',
+ org_name='Acme Corp',
+ inviter_name='John Doe',
+ role_name='admin',
+ invitation_token='inv-test-token-12345',
+ invitation_id=42,
+ )
+
+ message = smtp_client.sendmail.call_args[0][2]
+
+ assert 'Acme Corp' in message
+ assert 'John Doe' in message
+ assert 'admin' in message
+ assert "You're invited to join Acme Corp on OpenHands" in message
+
+
+class TestSMTPEmailServiceBudgetAlerts:
+ """Test cases for budget alert emails."""
+
+ def test_send_budget_alert_uses_smtp_when_configured(self):
+ smtp_client = MagicMock()
+
+ with (
+ patch.dict(
+ os.environ,
+ {
+ 'SMTP_HOST': 'smtp.example.com',
+ 'SMTP_PORT': '2525',
+ 'SMTP_FROM_EMAIL': '[email protected]',
+ },
+ clear=True,
+ ),
+ patch(
+ 'server.services.smtp_email_service.smtplib.SMTP',
+ return_value=smtp_client,
+ ) as mock_smtp,
+ ):
+ SMTPEmailService.send_budget_alert_email(
+ to_emails=['[email protected]'],
+ org_name='Acme Corp',
+ percentage=80.0,
+ current_spend=800.0,
+ monthly_limit=1000.0,
+ threshold=80,
+ )
+
+ mock_smtp.assert_called_once_with('smtp.example.com', 2525)
+ smtp_client.starttls.assert_called_once()
+ smtp_client.sendmail.assert_called_once()
+ send_args = smtp_client.sendmail.call_args[0]
+ assert send_args[0] == '[email protected]'
+ assert send_args[1] == ['[email protected]']
+
+ smtp_client.quit.assert_called_once()
+
+
+class TestSMTPEmailServiceHelpers:
+ """Tests for is_configured and build_invitation_url."""
+
+ def test_is_configured_false_without_smtp_host(self, monkeypatch):
+ monkeypatch.delenv('SMTP_HOST', raising=False)
+ from server.services.smtp_email_service import SMTPEmailService
+
+ assert SMTPEmailService.is_configured() is False
+
+ def test_is_configured_true_with_smtp_host(self, monkeypatch):
+ monkeypatch.setenv('SMTP_HOST', 'smtp.example.com')
+ from server.services.smtp_email_service import SMTPEmailService
+
+ assert SMTPEmailService.is_configured() is True
+
+ def test_build_invitation_url_normalizes_bare_hostname(self, monkeypatch):
+ """OHE charts set WEB_HOST as a bare hostname; links must get a scheme."""
+ monkeypatch.setenv('WEB_HOST', 'app.example.com')
+ from server.services.smtp_email_service import SMTPEmailService
+
+ url = SMTPEmailService.build_invitation_url('inv-token123')
+
+ assert url == (
+ 'https://app.example.com/api/organizations/members/invite/accept'
+ '?token=inv-token123'
+ )
+
+ def test_build_invitation_url_keeps_explicit_scheme(self, monkeypatch):
+ monkeypatch.setenv('WEB_HOST', 'https://app.example.com/')
+ from server.services.smtp_email_service import SMTPEmailService
+
+ url = SMTPEmailService.build_invitation_url('inv-token123')
+
+ assert url.startswith('https://app.example.com/api/')
diff --git a/openhands/app_server/web_client/default_web_client_config_injector.py b/openhands/app_server/web_client/default_web_client_config_injector.py
index 43657d16ea..f808672f4a 100644
--- a/openhands/app_server/web_client/default_web_client_config_injector.py
+++ b/openhands/app_server/web_client/default_web_client_config_injector.py
@@ -120,6 +120,15 @@ def _get_slack_enabled() -> bool:
)
+def _get_email_enabled() -> bool:
+ """Return whether transactional email delivery is configured."""
+ try:
+ from server.services.smtp_email_service import SMTPEmailService
+ except Exception:
+ return bool(os.getenv('SMTP_HOST', '').strip())
+ return SMTPEmailService.is_configured()
+
+
def _get_jira_dc_oauth_host() -> str | None:
"""Hostname of the Jira Data Center server when DC OAuth is configured.
@@ -221,6 +230,7 @@ class DefaultWebClientConfigInjector(WebClientConfigInjector):
}
)
slack_enabled: bool = Field(default_factory=_get_slack_enabled)
+ email_enabled: bool = Field(default_factory=_get_email_enabled)
jira_dc_oauth_host: str | None = Field(default_factory=_get_jira_dc_oauth_host)
jira_dc_service_account_managed: bool = Field(
default_factory=_is_jira_dc_service_account_managed
@@ -268,6 +278,7 @@ class DefaultWebClientConfigInjector(WebClientConfigInjector):
gitlab_enabled=self.gitlab_enabled,
provider_default_hosts=self.provider_default_hosts,
slack_enabled=self.slack_enabled,
+ email_enabled=self.email_enabled,
jira_dc_oauth_host=self.jira_dc_oauth_host,
jira_dc_service_account_managed=self.jira_dc_service_account_managed,
jira_dc_service_account_email=self.jira_dc_service_account_email,
diff --git a/tests/unit/app_server/test_default_web_client_config_injector.py b/tests/unit/app_server/test_default_web_client_config_injector.py
index 7c101d6dc3..daabae52a1 100644
--- a/tests/unit/app_server/test_default_web_client_config_injector.py
+++ b/tests/unit/app_server/test_default_web_client_config_injector.py
@@ -745,3 +745,31 @@ class TestGetSlackEnabled:
clear=True,
):
assert _get_slack_enabled() is False
+
+
+class TestGetEmailEnabled:
+ """Test cases for _get_email_enabled helper function."""
+
+ def test_returns_true_when_email_service_is_configured(self):
+ """Email is enabled when the SMTP integration is configured."""
+ from openhands.app_server.web_client.default_web_client_config_injector import (
+ _get_email_enabled,
+ )
+
+ with patch(
+ 'server.services.smtp_email_service.SMTPEmailService.is_configured',
+ return_value=True,
+ ):
+ assert _get_email_enabled() is True
+
+ def test_returns_false_when_email_service_is_not_configured(self):
+ """Email stays disabled when the SMTP integration is missing."""
+ from openhands.app_server.web_client.default_web_client_config_injector import (
+ _get_email_enabled,
+ )
+
+ with patch(
+ 'server.services.smtp_email_service.SMTPEmailService.is_configured',
+ return_value=False,
+ ):
+ assert _get_email_enabled() is False