SMTP settings
This commit is contained in:
@@ -0,0 +1,292 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import { useClient } from 'hooks/useClient';
|
||||||
|
import { useAuth } from 'hooks/useAuth';
|
||||||
|
|
||||||
|
type Provider = 'resend' | 'smtp' | 'mailhog';
|
||||||
|
|
||||||
|
type SmtpConfig = {
|
||||||
|
provider: Provider;
|
||||||
|
apiKey?: string;
|
||||||
|
host?: string;
|
||||||
|
port?: number;
|
||||||
|
username?: string;
|
||||||
|
password?: string;
|
||||||
|
secure?: boolean;
|
||||||
|
fromName: string;
|
||||||
|
fromEmail: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const PROVIDER_DEFAULTS: Record<Provider, Partial<SmtpConfig>> = {
|
||||||
|
mailhog: { host: 'localhost', port: 1025, secure: false, username: '', password: '' },
|
||||||
|
resend: { apiKey: '' },
|
||||||
|
smtp: { host: '', port: 587, secure: false, username: '', password: '' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SMTPSection = () => {
|
||||||
|
const client = useClient();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { user } = useAuth();
|
||||||
|
|
||||||
|
const { data: config, isLoading } = useQuery({
|
||||||
|
queryKey: ['SMTP_CONFIG'],
|
||||||
|
queryFn: () => client.get<SmtpConfig | null>('/server-settings/smtp'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const [provider, setProvider] = useState<Provider>('mailhog');
|
||||||
|
const [apiKey, setApiKey] = useState('');
|
||||||
|
const [host, setHost] = useState('localhost');
|
||||||
|
const [port, setPort] = useState('1025');
|
||||||
|
const [username, setUsername] = useState('');
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
const [secure, setSecure] = useState(false);
|
||||||
|
const [fromName, setFromName] = useState('officerdev');
|
||||||
|
const [fromEmail, setFromEmail] = useState('no-reply@officer.dev');
|
||||||
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
|
const [isTestingConnection, setIsTestingConnection] = useState(false);
|
||||||
|
const [testEmail, setTestEmail] = useState(user?.email ?? '');
|
||||||
|
const [isTesting, setIsTesting] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!config) return;
|
||||||
|
setProvider(config.provider);
|
||||||
|
setApiKey(config.apiKey ?? '');
|
||||||
|
setHost(config.host ?? '');
|
||||||
|
setPort(String(config.port ?? 587));
|
||||||
|
setUsername(config.username ?? '');
|
||||||
|
setPassword(config.password ?? '');
|
||||||
|
setSecure(config.secure ?? false);
|
||||||
|
setFromName(config.fromName || 'officerdev');
|
||||||
|
setFromEmail(config.fromEmail || 'no-reply@officer.dev');
|
||||||
|
}, [config]);
|
||||||
|
|
||||||
|
const handleProviderChange = (v: Provider) => {
|
||||||
|
setProvider(v);
|
||||||
|
const defaults = PROVIDER_DEFAULTS[v];
|
||||||
|
if (defaults.host !== undefined) setHost(defaults.host);
|
||||||
|
if (defaults.port !== undefined) setPort(String(defaults.port));
|
||||||
|
if (defaults.secure !== undefined) setSecure(defaults.secure);
|
||||||
|
if (defaults.username !== undefined) setUsername(defaults.username);
|
||||||
|
if (defaults.password !== undefined) setPassword(defaults.password);
|
||||||
|
if (defaults.apiKey !== undefined) setApiKey(defaults.apiKey);
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildConfig = (): SmtpConfig => ({
|
||||||
|
provider,
|
||||||
|
fromName,
|
||||||
|
fromEmail,
|
||||||
|
...(provider === 'resend'
|
||||||
|
? { apiKey }
|
||||||
|
: { host, port: parseInt(port) || 587, username, password, secure }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (isSaving) return;
|
||||||
|
setIsSaving(true);
|
||||||
|
try {
|
||||||
|
await client.put('/server-settings/smtp', buildConfig());
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['SMTP_CONFIG'] });
|
||||||
|
toast.success('SMTP settings saved');
|
||||||
|
} catch {
|
||||||
|
toast.error('Failed to save SMTP settings');
|
||||||
|
} finally {
|
||||||
|
setIsSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTestConnection = async () => {
|
||||||
|
if (isTestingConnection) return;
|
||||||
|
setIsTestingConnection(true);
|
||||||
|
try {
|
||||||
|
await client.post('/server-settings/smtp/test-connection');
|
||||||
|
toast.success('Connection successful');
|
||||||
|
} catch (err: unknown) {
|
||||||
|
const raw = (err as { message?: string })?.message;
|
||||||
|
let msg = 'Connection failed';
|
||||||
|
try { if (raw) msg = JSON.parse(raw).error ?? msg; } catch { /* ignore */ }
|
||||||
|
toast.error(msg);
|
||||||
|
} finally {
|
||||||
|
setIsTestingConnection(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTest = async () => {
|
||||||
|
if (isTesting || !testEmail) return;
|
||||||
|
setIsTesting(true);
|
||||||
|
try {
|
||||||
|
const result = await client.post<{ success?: boolean; error?: string }>('/server-settings/smtp/test', { ...buildConfig(), to: testEmail });
|
||||||
|
if (result.error) {
|
||||||
|
toast.error(result.error);
|
||||||
|
} else {
|
||||||
|
toast.success(`Test email sent to ${testEmail}`);
|
||||||
|
}
|
||||||
|
} catch (err: unknown) {
|
||||||
|
const raw = (err as { message?: string })?.message;
|
||||||
|
let msg = 'Failed to send test email';
|
||||||
|
try { if (raw) msg = JSON.parse(raw).error ?? msg; } catch { /* ignore */ }
|
||||||
|
toast.error(msg);
|
||||||
|
} finally {
|
||||||
|
setIsTesting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoading) return <p className="text-sm text-duck-dark/40">Loading...</p>;
|
||||||
|
|
||||||
|
const showSmtpFields = provider === 'smtp' || provider === 'mailhog';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="grid gap-4">
|
||||||
|
<Label className="grid gap-2">
|
||||||
|
<span className="text-duck-dark/70 dark:text-foreground/70">Provider</span>
|
||||||
|
<Select value={provider} onValueChange={(v) => handleProviderChange(v as Provider)}>
|
||||||
|
<SelectTrigger className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark dark:text-foreground">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="z-[600]">
|
||||||
|
<SelectItem value="mailhog">MailHog (local testing)</SelectItem>
|
||||||
|
<SelectItem value="resend">Resend</SelectItem>
|
||||||
|
<SelectItem value="smtp">Custom SMTP</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Label>
|
||||||
|
|
||||||
|
{provider === 'resend' && (
|
||||||
|
<Label className="grid gap-2">
|
||||||
|
<span className="text-duck-dark/70 dark:text-foreground/70">API Key</span>
|
||||||
|
<Input
|
||||||
|
type="password"
|
||||||
|
className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark dark:text-foreground placeholder:text-duck-dark/40"
|
||||||
|
placeholder="re_..."
|
||||||
|
value={apiKey}
|
||||||
|
onChange={(ev) => setApiKey(ev.target.value)}
|
||||||
|
/>
|
||||||
|
</Label>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showSmtpFields && (
|
||||||
|
<>
|
||||||
|
<div className="grid grid-cols-[1fr_auto] gap-2">
|
||||||
|
<Label className="grid gap-2">
|
||||||
|
<span className="text-duck-dark/70 dark:text-foreground/70">Host</span>
|
||||||
|
<Input
|
||||||
|
className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark dark:text-foreground placeholder:text-duck-dark/40"
|
||||||
|
placeholder="smtp.example.com"
|
||||||
|
value={host}
|
||||||
|
onChange={(ev) => setHost(ev.target.value)}
|
||||||
|
/>
|
||||||
|
</Label>
|
||||||
|
<Label className="grid gap-2">
|
||||||
|
<span className="text-duck-dark/70 dark:text-foreground/70">Port</span>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
className="h-11 w-24 bg-background/60 border-duck-dark/20 text-duck-dark dark:text-foreground"
|
||||||
|
value={port}
|
||||||
|
onChange={(ev) => setPort(ev.target.value)}
|
||||||
|
/>
|
||||||
|
</Label>
|
||||||
|
</div>
|
||||||
|
{provider === 'smtp' && (
|
||||||
|
<>
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
<Label className="grid gap-2">
|
||||||
|
<span className="text-duck-dark/70 dark:text-foreground/70">Username</span>
|
||||||
|
<Input
|
||||||
|
className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark dark:text-foreground placeholder:text-duck-dark/40"
|
||||||
|
placeholder="user@example.com"
|
||||||
|
value={username}
|
||||||
|
onChange={(ev) => setUsername(ev.target.value)}
|
||||||
|
/>
|
||||||
|
</Label>
|
||||||
|
<Label className="grid gap-2">
|
||||||
|
<span className="text-duck-dark/70 dark:text-foreground/70">Password</span>
|
||||||
|
<Input
|
||||||
|
type="password"
|
||||||
|
className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark dark:text-foreground"
|
||||||
|
value={password}
|
||||||
|
onChange={(ev) => setPassword(ev.target.value)}
|
||||||
|
/>
|
||||||
|
</Label>
|
||||||
|
</div>
|
||||||
|
<Label className="flex items-center gap-3">
|
||||||
|
<Switch checked={secure} onCheckedChange={setSecure} />
|
||||||
|
<span className="text-duck-dark/70 dark:text-foreground/70">TLS / SSL</span>
|
||||||
|
</Label>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
<Label className="grid gap-2">
|
||||||
|
<span className="text-duck-dark/70 dark:text-foreground/70">From Name</span>
|
||||||
|
<Input
|
||||||
|
className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark dark:text-foreground placeholder:text-duck-dark/40"
|
||||||
|
value={fromName}
|
||||||
|
onChange={(ev) => setFromName(ev.target.value)}
|
||||||
|
/>
|
||||||
|
</Label>
|
||||||
|
<Label className="grid gap-2">
|
||||||
|
<span className="text-duck-dark/70 dark:text-foreground/70">From Email</span>
|
||||||
|
<Input
|
||||||
|
type="email"
|
||||||
|
className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark dark:text-foreground placeholder:text-duck-dark/40"
|
||||||
|
value={fromEmail}
|
||||||
|
onChange={(ev) => setFromEmail(ev.target.value)}
|
||||||
|
/>
|
||||||
|
</Label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={isSaving}
|
||||||
|
className="flex-1 h-11 bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold transition-all duration-200 hover:scale-105 cursor-pointer disabled:opacity-50 disabled:hover:scale-100"
|
||||||
|
>
|
||||||
|
{isSaving ? 'Saving...' : 'Save'}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleTestConnection}
|
||||||
|
disabled={isTestingConnection}
|
||||||
|
className="h-11 cursor-pointer disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isTestingConnection ? 'Testing...' : 'Test'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border-t border-duck-dark/10 dark:border-foreground/10 pt-4 mt-1">
|
||||||
|
<span className="text-sm font-medium text-duck-dark dark:text-foreground">Send Test Email</span>
|
||||||
|
<div className="flex items-center gap-2 mt-2">
|
||||||
|
<Input
|
||||||
|
type="email"
|
||||||
|
className="h-9 bg-background/60 border-duck-dark/20 text-duck-dark dark:text-foreground placeholder:text-duck-dark/40 flex-1"
|
||||||
|
placeholder="recipient@example.com"
|
||||||
|
value={testEmail}
|
||||||
|
onChange={(ev) => setTestEmail(ev.target.value)}
|
||||||
|
onKeyDown={(ev) => {
|
||||||
|
if (ev.key === 'Enter') handleTest();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={handleTest}
|
||||||
|
disabled={isTesting || !testEmail}
|
||||||
|
className="h-9 cursor-pointer disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isTesting ? 'Sending...' : 'Send'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState, useEffect, useMemo, useCallback, type DragEvent } from 'react';
|
import { useState, useEffect, useMemo, useCallback, type DragEvent } from 'react';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { Terminal, Eye, Bot, Settings, X, Plus } from 'lucide-react';
|
import { Terminal, Eye, Bot, Settings, X, Plus, Mail } from 'lucide-react';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
@@ -19,6 +19,7 @@ import { usePiModels, useVisiblePiModels, modelKey, getProviderDisplayName, type
|
|||||||
import type { UserSettings } from 'state/useSettings';
|
import type { UserSettings } from 'state/useSettings';
|
||||||
import { AIHarnessesSection } from './ServerSettings/AIHarnessesSection';
|
import { AIHarnessesSection } from './ServerSettings/AIHarnessesSection';
|
||||||
import { RUN_COMMAND_CHANNEL, type RunCommandState } from './ServerSettings/run-command-channel';
|
import { RUN_COMMAND_CHANNEL, type RunCommandState } from './ServerSettings/run-command-channel';
|
||||||
|
import { SMTPSection } from './ServerSettings/SMTPSection';
|
||||||
|
|
||||||
const PROVIDER_DISPLAY: Record<string, string> = {
|
const PROVIDER_DISPLAY: Record<string, string> = {
|
||||||
anthropic: 'Anthropic',
|
anthropic: 'Anthropic',
|
||||||
@@ -51,6 +52,13 @@ const groups: SettingsSectionGroup[] = [
|
|||||||
{ key: 'chat-defaults', icon: Terminal, title: 'Chat Defaults', description: 'Model, prompt, and temperature', content: <ChatDefaultsSection /> },
|
{ key: 'chat-defaults', icon: Terminal, title: 'Chat Defaults', description: 'Model, prompt, and temperature', content: <ChatDefaultsSection /> },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
label: 'Email',
|
||||||
|
icon: Mail,
|
||||||
|
sections: [
|
||||||
|
{ key: 'smtp', icon: Mail, title: 'SMTP', description: 'Email delivery provider', content: <SMTPSection /> },
|
||||||
|
],
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const { Sidebar, Content } = createSettingsPanelComponents({
|
const { Sidebar, Content } = createSettingsPanelComponents({
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { opencodeRouter } from './opencode';
|
|||||||
import { piMonoRouter } from './pi-mono';
|
import { piMonoRouter } from './pi-mono';
|
||||||
import { applicationsRouter } from './applications';
|
import { applicationsRouter } from './applications';
|
||||||
import { resourcesRouter } from './resources';
|
import { resourcesRouter } from './resources';
|
||||||
|
import { smtpRouter } from './smtp';
|
||||||
|
|
||||||
const configDir = `${homedir()}/.config/officer.dev`;
|
const configDir = `${homedir()}/.config/officer.dev`;
|
||||||
export const settingsPath = `${configDir}/server-settings.json`;
|
export const settingsPath = `${configDir}/server-settings.json`;
|
||||||
@@ -26,6 +27,7 @@ serverSettingsRouter.route('/opencode', opencodeRouter);
|
|||||||
serverSettingsRouter.route('/pi-mono', piMonoRouter);
|
serverSettingsRouter.route('/pi-mono', piMonoRouter);
|
||||||
serverSettingsRouter.route('/applications', applicationsRouter);
|
serverSettingsRouter.route('/applications', applicationsRouter);
|
||||||
serverSettingsRouter.route('/resources', resourcesRouter);
|
serverSettingsRouter.route('/resources', resourcesRouter);
|
||||||
|
serverSettingsRouter.route('/smtp', smtpRouter);
|
||||||
|
|
||||||
serverSettingsRouter.get('/settings', async (ctx) => {
|
serverSettingsRouter.get('/settings', async (ctx) => {
|
||||||
const settings = await Bun.file(settingsPath).json();
|
const settings = await Bun.file(settingsPath).json();
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { createTransport } from 'nodemailer';
|
||||||
|
import { createRouter } from '../../create-router';
|
||||||
|
import { settingsPath } from './server-settings';
|
||||||
|
import { getTransport } from 'emailer';
|
||||||
|
|
||||||
|
type SmtpConfig = {
|
||||||
|
provider: 'resend' | 'smtp' | 'mailhog';
|
||||||
|
apiKey?: string;
|
||||||
|
host?: string;
|
||||||
|
port?: number;
|
||||||
|
username?: string;
|
||||||
|
password?: string;
|
||||||
|
secure?: boolean;
|
||||||
|
fromName: string;
|
||||||
|
fromEmail: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function maskSecret(value: string | undefined): string | undefined {
|
||||||
|
if (!value || value.length < 8) return value ? '****' : undefined;
|
||||||
|
return value.slice(0, 4) + '****' + value.slice(-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
function serializeConfig(smtp: SmtpConfig) {
|
||||||
|
return {
|
||||||
|
provider: smtp.provider,
|
||||||
|
apiKey: maskSecret(smtp.apiKey),
|
||||||
|
host: smtp.host,
|
||||||
|
port: smtp.port,
|
||||||
|
username: smtp.username,
|
||||||
|
password: maskSecret(smtp.password),
|
||||||
|
secure: smtp.secure,
|
||||||
|
fromName: smtp.fromName,
|
||||||
|
fromEmail: smtp.fromEmail,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildTransportUrl(config: SmtpConfig): string {
|
||||||
|
if (config.provider === 'resend') {
|
||||||
|
return `smtps://resend:${config.apiKey}@smtp.resend.com:465`;
|
||||||
|
}
|
||||||
|
if (config.provider === 'mailhog') {
|
||||||
|
return `smtp://${config.host ?? 'localhost'}:${config.port ?? 1025}`;
|
||||||
|
}
|
||||||
|
const auth = config.username ? `${encodeURIComponent(config.username)}:${encodeURIComponent(config.password ?? '')}@` : '';
|
||||||
|
const protocol = config.secure ? 'smtps' : 'smtp';
|
||||||
|
return `${protocol}://${auth}${config.host}:${config.port ?? 587}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const smtpRouter = createRouter();
|
||||||
|
|
||||||
|
smtpRouter.get('/', async (ctx) => {
|
||||||
|
const settings = await Bun.file(settingsPath).json().catch(() => ({}));
|
||||||
|
const smtp: SmtpConfig | undefined = settings.smtp;
|
||||||
|
if (smtp) return ctx.json(serializeConfig(smtp));
|
||||||
|
return ctx.json(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
smtpRouter.put('/', async (ctx) => {
|
||||||
|
const body = await ctx.req.json<SmtpConfig>();
|
||||||
|
const settings = await Bun.file(settingsPath).json().catch(() => ({}));
|
||||||
|
|
||||||
|
const existing: SmtpConfig | undefined = settings.smtp;
|
||||||
|
if (existing) {
|
||||||
|
if (body.apiKey && body.apiKey.includes('****')) body.apiKey = existing.apiKey;
|
||||||
|
if (body.password && body.password.includes('****')) body.password = existing.password;
|
||||||
|
}
|
||||||
|
|
||||||
|
settings.smtp = body;
|
||||||
|
await Bun.write(settingsPath, JSON.stringify(settings, null, 2));
|
||||||
|
return ctx.json({ success: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
smtpRouter.post('/test-connection', async (ctx) => {
|
||||||
|
try {
|
||||||
|
const { transport } = await getTransport();
|
||||||
|
await transport.verify();
|
||||||
|
return ctx.json({ success: true });
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : 'Unknown error';
|
||||||
|
return ctx.json({ error: message }, 500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
smtpRouter.post('/test', async (ctx) => {
|
||||||
|
const body = await ctx.req.json<SmtpConfig & { to: string }>();
|
||||||
|
if (!body.to) return ctx.json({ error: 'Recipient address required' }, 400);
|
||||||
|
|
||||||
|
// Resolve masked secrets from saved config
|
||||||
|
const settings = await Bun.file(settingsPath).json().catch(() => ({}));
|
||||||
|
const saved: SmtpConfig | undefined = settings.smtp;
|
||||||
|
if (saved) {
|
||||||
|
if (body.apiKey?.includes('****')) body.apiKey = saved.apiKey;
|
||||||
|
if (body.password?.includes('****')) body.password = saved.password;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = buildTransportUrl(body);
|
||||||
|
const transport = createTransport(url);
|
||||||
|
const from = `${body.fromName} <${body.fromEmail}>`;
|
||||||
|
|
||||||
|
await transport.sendMail({
|
||||||
|
from,
|
||||||
|
to: body.to,
|
||||||
|
subject: 'Officer Test Email',
|
||||||
|
html: '<h2>Officer Test Email</h2><p>If you received this, your email configuration is working correctly.</p>',
|
||||||
|
});
|
||||||
|
return ctx.json({ success: true });
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : 'Unknown error';
|
||||||
|
return ctx.json({ error: message }, 500);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { render } from '@react-email/render';
|
import { render } from '@react-email/render';
|
||||||
import transport from './transport';
|
import { getTransport } from './transport';
|
||||||
import { templates } from './templates';
|
import { templates } from './templates';
|
||||||
|
|
||||||
type SendMailArgs = {
|
type SendMailArgs = {
|
||||||
@@ -10,22 +10,15 @@ type SendMailArgs = {
|
|||||||
from?: string;
|
from?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function sendMail({ template, subject, to, data, from = 'Officer <no-reply@officer.dev>' }: SendMailArgs) {
|
export async function sendMail({ template, subject, to, data, from }: SendMailArgs) {
|
||||||
const options = {
|
const { transport, from: configuredFrom } = await getTransport();
|
||||||
from,
|
const sender = from ?? configuredFrom ?? 'officerdev <no-reply@officer.dev>';
|
||||||
to,
|
|
||||||
subject,
|
|
||||||
};
|
|
||||||
|
|
||||||
const theTemplate = templates[template];
|
const theTemplate = templates[template];
|
||||||
const templated = theTemplate(data);
|
const templated = theTemplate(data);
|
||||||
|
|
||||||
// try {
|
|
||||||
const emailHtml = await render(templated);
|
const emailHtml = await render(templated);
|
||||||
transport.sendMail({ ...options, html: emailHtml });
|
await transport.sendMail({ from: sender, to, subject, html: emailHtml });
|
||||||
// } catch (ex) {
|
|
||||||
// console.log("ex", ex);
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export { templates };
|
export { getTransport, templates };
|
||||||
|
|||||||
@@ -1,6 +1,70 @@
|
|||||||
import { createTransport } from 'nodemailer';
|
import { createTransport, type Transporter } from 'nodemailer';
|
||||||
|
import { homedir } from 'node:os';
|
||||||
|
|
||||||
const { MAIL_TRANSPORT } = process.env;
|
const { MAIL_TRANSPORT } = process.env;
|
||||||
|
|
||||||
const transport = createTransport(MAIL_TRANSPORT);
|
type SmtpConfig = {
|
||||||
|
provider: 'resend' | 'smtp' | 'mailhog';
|
||||||
|
apiKey?: string;
|
||||||
|
host?: string;
|
||||||
|
port?: number;
|
||||||
|
username?: string;
|
||||||
|
password?: string;
|
||||||
|
secure?: boolean;
|
||||||
|
fromName: string;
|
||||||
|
fromEmail: string;
|
||||||
|
};
|
||||||
|
|
||||||
export default transport;
|
const settingsPath = `${homedir()}/.config/officer.dev/server-settings.json`;
|
||||||
|
|
||||||
|
let cachedTransport: Transporter | null = null;
|
||||||
|
let cachedConfigHash: string | null = null;
|
||||||
|
|
||||||
|
function buildTransportUrl(config: SmtpConfig): string {
|
||||||
|
if (config.provider === 'resend') {
|
||||||
|
return `smtps://resend:${config.apiKey}@smtp.resend.com:465`;
|
||||||
|
}
|
||||||
|
if (config.provider === 'mailhog') {
|
||||||
|
return `smtp://${config.host ?? 'localhost'}:${config.port ?? 1025}`;
|
||||||
|
}
|
||||||
|
const auth = config.username ? `${encodeURIComponent(config.username)}:${encodeURIComponent(config.password ?? '')}@` : '';
|
||||||
|
const protocol = config.secure ? 'smtps' : 'smtp';
|
||||||
|
return `${protocol}://${auth}${config.host}:${config.port ?? 587}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
type TransportResult = {
|
||||||
|
transport: Transporter;
|
||||||
|
from: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getTransport(): Promise<TransportResult> {
|
||||||
|
try {
|
||||||
|
const file = Bun.file(settingsPath);
|
||||||
|
if (await file.exists()) {
|
||||||
|
const settings = await file.json();
|
||||||
|
const smtp: SmtpConfig | undefined = settings.smtp;
|
||||||
|
if (smtp) {
|
||||||
|
const hash = JSON.stringify(smtp);
|
||||||
|
if (cachedTransport && cachedConfigHash === hash) {
|
||||||
|
return { transport: cachedTransport, from: `${smtp.fromName} <${smtp.fromEmail}>` };
|
||||||
|
}
|
||||||
|
const url = buildTransportUrl(smtp);
|
||||||
|
cachedTransport = createTransport(url);
|
||||||
|
cachedConfigHash = hash;
|
||||||
|
return { transport: cachedTransport, from: `${smtp.fromName} <${smtp.fromEmail}>` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Fall through to env var
|
||||||
|
}
|
||||||
|
|
||||||
|
if (MAIL_TRANSPORT) {
|
||||||
|
if (!cachedTransport || cachedConfigHash !== 'env') {
|
||||||
|
cachedTransport = createTransport(MAIL_TRANSPORT);
|
||||||
|
cachedConfigHash = 'env';
|
||||||
|
}
|
||||||
|
return { transport: cachedTransport, from: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('No email transport configured');
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user