타입이 지정된 React Email 템플릿의 트랜잭션 이메일: Resend, SMTP, 개발 시 콘솔
설치
genpm add @core/email포함 내용
- src/lib/email/에 소스 코드, 파일 9개. (12.9kB)
- src/lib/email/AGENTS.md에 AI 규칙, 그리고 IDE 규칙 파일.
- .env.example에 추가되는 환경 변수: RESEND_API_KEY, EMAIL_FROM, APP_NAME.
README
@core/email
Transactional email with typed React Email templates: Resend, SMTP or console in dev
A GenPM module: source code + AI rules + MCP config, injected into your project instead of hidden in node_modules. The code lands in src/lib/email, pinned to a verified commit, and you own it.
Install
genpm add @core/emailNo genpm yet? curl -fsSL https://genpm.net/install.sh | sh (macOS/Linux), irm https://genpm.net/install.ps1 | iex (Windows), or one-off with npx @genpm-net/cli add @core/email.
Or let your AI agent do it: run genpm mcp setup once, then ask "add @core/email with genpm" in Claude Code, Cursor, VS Code, Windsurf, Codex or Gemini CLI. It shows you a dry-run plan before writing anything.
What it does
Transactional email with typed templates: sendEmail('welcome', { to, props }). Providers: Resend (default), SMTP
(optional, via nodemailer) and a console provider for development. Templates use React Email. No marketing lists,
no queues, no tracking pixels.
Setup
After genpm add, follow these steps (your AI agent finds the same steps in src/lib/email/AGENTS.md and can do them for you):
- Env:
EMAIL_FROM("App <hello@yourdomain.com>") andRESEND_API_KEY(verify the domain in Resend first). WithoutRESEND_API_KEY, outside production, emails are printed to the console. In production (next start) that fallback throws so mail is never lost silently; setEMAIL_PROVIDER=consoleto print them there too (local tests). OptionalAPP_NAME: brand name shown in the email layout (defaultApp).@types/reactis only needed at build time: move it to devDependencies if GenPM added it to dependencies. SMTP instead:EMAIL_PROVIDER=smtp,SMTP_URL=smtps://user:pass@host:465and installnodemailer. - Send from server code only:
import { sendEmail } from './lib/email/index.ts'; await sendEmail('welcome', { to: user.email, props: { name: user.name, appUrl: 'https://app.example.com' } }); - With
@core/auth(≥ 1.1.0): sendwelcomefrom itsonLoginhook whenisNewUseris true:app.route('/auth', authRoutes({ onLogin: ({ user, isNewUser }) => isNewUser && user.email ? sendEmail('welcome', { to: user.email, props: { name: user.name, appUrl: process.env.APP_URL ?? '' } }).then(() => undefined) : undefined, })); - Verify: run the app without
RESEND_API_KEYand check the console output.
What's inside
Paths are relative to src/lib/email.
index.ts— public API:sendEmail,renderEmail,setEmailProvider, provider factories,TemplateProps.send.ts— the template registry (templates) andsendEmail.templates/*.ts—welcome,magicLink,receipt, plus the sharedlayout.ts.providers.ts—EmailProviderinterface and implementations.
At a glance
- npm dependencies (proposed, never installed without asking):
resend,@react-email/components,@react-email/render,react,@types/react - Environment variables (added to
.env.example):RESEND_API_KEY,EMAIL_FROM,APP_NAME - AI rules:
AGENTS.md, loaded by your agent only when it works insrc/lib/email
Security
GenPM installs a 40-character commit SHA (never a branch), verifies an Ed25519-signed manifest, never runs install scripts and scans AI rules for prompt injection. Details: genpm.net/docs/security.
License
이것이 AI가 src/lib/email에서 작업할 때 읽는 내용 그대로입니다. 그 외에는 컨텍스트에 아무것도 추가되지 않습니다.
@core/email — rules for AI agents
Purpose
Transactional email with typed templates: sendEmail('welcome', { to, props }). Providers: Resend (default), SMTP
(optional, via nodemailer) and a console provider for development. Templates use React Email. No marketing lists,
no queues, no tracking pixels.
Map
index.ts— public API:sendEmail,renderEmail,setEmailProvider, provider factories,TemplateProps.send.ts— the template registry (templates) andsendEmail.templates/*.ts—welcome,magicLink,receipt, plus the sharedlayout.ts.providers.ts—EmailProviderinterface and implementations.
Integration
- Env:
EMAIL_FROM("App <hello@yourdomain.com>") andRESEND_API_KEY(verify the domain in Resend first). WithoutRESEND_API_KEY, outside production, emails are printed to the console. In production (next start) that fallback throws so mail is never lost silently; setEMAIL_PROVIDER=consoleto print them there too (local tests). OptionalAPP_NAME: brand name shown in the email layout (defaultApp).@types/reactis only needed at build time: move it to devDependencies if GenPM added it to dependencies. SMTP instead:EMAIL_PROVIDER=smtp,SMTP_URL=smtps://user:pass@host:465and installnodemailer. - Send from server code only:
import { sendEmail } from './lib/email/index.ts'; await sendEmail('welcome', { to: user.email, props: { name: user.name, appUrl: 'https://app.example.com' } }); - With
@core/auth(≥ 1.1.0): sendwelcomefrom itsonLoginhook whenisNewUseris true:app.route('/auth', authRoutes({ onLogin: ({ user, isNewUser }) => isNewUser && user.email ? sendEmail('welcome', { to: user.email, props: { name: user.name, appUrl: process.env.APP_URL ?? '' } }).then(() => undefined) : undefined, })); - Verify: run the app without
RESEND_API_KEYand check the console output.
Conventions
- New template: create
templates/<name>.tsexporting{ subject(props), render(props) }built withcreateElement as h(no JSX, so it works with anyjsxImportSource), then add it totemplatesandTemplatePropsinsend.ts. TypeScript then enforces its props everywhere. - Amounts in the currency minor unit (cents; whole yen for JPY; 3 decimals for KWD); links absolute (
https://…). - Keep
sendEmailcalls out of request hot paths when possible (after the response, or in a job).
Don't
- Don't send from the browser or expose
RESEND_API_KEYto client code. - Don't interpolate untrusted HTML into templates; pass plain strings (React escapes them).
- Don't log full email bodies in production (they may contain sign-in links).
# @core/email — rules for AI agents
## Purpose
Transactional email with typed templates: `sendEmail('welcome', { to, props })`. Providers: Resend (default), SMTP
(optional, via `nodemailer`) and a console provider for development. Templates use React Email. No marketing lists,
no queues, no tracking pixels.
## Map
- `index.ts` — public API: `sendEmail`, `renderEmail`, `setEmailProvider`, provider factories, `TemplateProps`.
- `send.ts` — the template registry (`templates`) and `sendEmail`.
- `templates/*.ts` — `welcome`, `magicLink`, `receipt`, plus the shared `layout.ts`.
- `providers.ts` — `EmailProvider` interface and implementations.
## Integration
1. Env: `EMAIL_FROM` (`"App <hello@yourdomain.com>"`) and `RESEND_API_KEY` (verify the domain in Resend first).
Without `RESEND_API_KEY`, outside production, emails are printed to the console. In production (`next start`) that
fallback throws so mail is never lost silently; set `EMAIL_PROVIDER=console` to print them there too (local tests).
Optional `APP_NAME`: brand name shown in the email layout (default `App`).
`@types/react` is only needed at build time: move it to devDependencies if GenPM added it to dependencies.
SMTP instead: `EMAIL_PROVIDER=smtp`, `SMTP_URL=smtps://user:pass@host:465` and install `nodemailer`.
2. Send from server code only:
```ts
import { sendEmail } from './lib/email/index.ts';
await sendEmail('welcome', { to: user.email, props: { name: user.name, appUrl: 'https://app.example.com' } });
```
3. With `@core/auth` (≥ 1.1.0): send `welcome` from its `onLogin` hook when `isNewUser` is true:
```ts
app.route('/auth', authRoutes({
onLogin: ({ user, isNewUser }) =>
isNewUser && user.email ? sendEmail('welcome', { to: user.email, props: { name: user.name, appUrl: process.env.APP_URL ?? '' } }).then(() => undefined) : undefined,
}));
```
4. Verify: run the app without `RESEND_API_KEY` and check the console output.
## Conventions
- New template: create `templates/<name>.ts` exporting `{ subject(props), render(props) }` built with
`createElement as h` (no JSX, so it works with any `jsxImportSource`), then add it to `templates` and
`TemplateProps` in `send.ts`. TypeScript then enforces its props everywhere.
- Amounts in the currency minor unit (cents; whole yen for JPY; 3 decimals for KWD); links absolute (`https://…`).
- Keep `sendEmail` calls out of request hot paths when possible (after the response, or in a job).
## Don't
- Don't send from the browser or expose `RESEND_API_KEY` to client code.
- Don't interpolate untrusted HTML into templates; pass plain strings (React escapes them).
- Don't log full email bodies in production (they may contain sign-in links).
.genpmignore 적용 후 주입될 정확한 트리입니다. 고정 대상:
// Proveedores de envío. Elige con EMAIL_PROVIDER (resend | smtp | console); por defecto Resend si hay
// RESEND_API_KEY y, si no, consola (solo fuera de producción, salvo `EMAIL_PROVIDER=console` explícito).
import { Resend } from 'resend';
export type EmailMessage = { from: string; to: string | string[]; subject: string; html: string; text: string; replyTo?: string };
export type SendResult = { id: string | null };
export interface EmailProvider {
readonly name: string;
send(message: EmailMessage): Promise<SendResult>;
}
export function resendProvider(apiKey: string = process.env.RESEND_API_KEY ?? ''): EmailProvider {
if (!apiKey) throw new Error('RESEND_API_KEY is not set (see .env.example)');
const client = new Resend(apiKey);
return {
name: 'resend',
async send(m) {
const { data, error } = await client.emails.send({
from: m.from,
to: m.to,
subject: m.subject,
html: m.html,
text: m.text,
...(m.replyTo ? { replyTo: m.replyTo } : {}),
});
if (error) throw new Error(`Resend: ${error.message}`);
return { id: data?.id ?? null };
},
};
}
/** SMTP con `nodemailer` (instálalo solo si lo usas): SMTP_URL=smtps://user:pass@smtp.example.com:465 */
export function smtpProvider(url: string = process.env.SMTP_URL ?? ''): EmailProvider {
if (!url) throw new Error('SMTP_URL is not set');
let transport: { sendMail(m: Record<string, unknown>): Promise<{ messageId?: string }> } | null = null;
return {
name: 'smtp',
async send(m) {
if (!transport) {
const name = 'nodemailer';
const mod = (await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ name)) as { default: { createTransport(url: string): NonNullable<typeof transport> } };
transport = mod.default.createTransport(url);
}
const info = await transport.sendMail({ from: m.from, to: m.to, subject: m.subject, html: m.html, text: m.text, replyTo: m.replyTo });
return { id: info.messageId ?? null };
},
};
}
/** Modo dev: imprime el correo (texto plano) en vez de enviarlo. */
export function consoleProvider(log: (line: string) => void = console.info): EmailProvider {
return {
name: 'console',
async send(m) {
log(`[email] to=${[m.to].flat().join(',')} subject=${JSON.stringify(m.subject)}\n${m.text}`);
return { id: null };
},
};
}
export function defaultProvider(env: NodeJS.ProcessEnv = process.env): EmailProvider {
const choice = env.EMAIL_PROVIDER ?? (env.RESEND_API_KEY ? 'resend' : 'console');
if (choice === 'resend') return resendProvider(env.RESEND_API_KEY);
if (choice === 'smtp') return smtpProvider(env.SMTP_URL);
// En producción la consola solo se usa si se pide (p. ej. `next start` en local o un entorno de pruebas): por defecto
// se falla para no perder correos en silencio.
if (env.NODE_ENV === 'production' && env.EMAIL_PROVIDER !== 'console') throw new Error('No email provider configured in production (set RESEND_API_KEY, or EMAIL_PROVIDER=console to print emails)');
return consoleProvider();
}
이 패키지는 MCP 서버를 선언하지 않습니다.
- genpm
- 없음
- npm
- @react-email/components ^1.0.12@react-email/render ^2.1.0@types/react ^19.0.0react ^19.0.0resend ^6.32.0
- 제안됨
- GenPM은 npm 명령을 제안하고, 동의한 경우에만 실행합니다.
- 검사
- 검사 통과 · 문제 0건
- 커밋
- v1.0.4 → cbc155965170820a92134ecf8b4b32411a629f5d · 가져온 뒤 검증됨
- 스크립트
- 없음. GenPM은 패키지 코드를 절대 실행하지 않습니다.
- 라이선스
- MIT
- 품질
- 100/100
- 인정된 라이선스충족
- AGENTS.md에 목적 설명충족
- AGENTS.md에 통합 단계충족
- AGENTS.md에 규칙 또는 금지 사항충족
- 테스트 포함충족
- 보안 검사 통과충족
- 최근 6개월 내 게시충족
- 인증된 게시자충족
- 요약과 키워드충족
- 신고
- 문제가 있나요?