src / smtp.ts
import nodemailer from "nodemailer";
export interface SmtpConfig {
host: string;
port: number;
user: string;
password: string;
}
export interface DraftOptions {
from: string;
to: string;
cc?: string;
subject: string;
body: string;
inReplyTo?: string;
references?: string;
}
function createTransport(cfg: SmtpConfig) {
return nodemailer.createTransport({
host: cfg.host,
port: cfg.port,
secure: cfg.port === 465,
auth: { user: cfg.user, pass: cfg.password },
connectionTimeout: 20_000,
greetingTimeout: 20_000,
socketTimeout: 60_000,
});
}
export async function verifySmtpConnection(cfg: SmtpConfig): Promise<void> {
const transport = createTransport(cfg);
try {
await transport.verify();
} finally {
transport.close();
}
}
export async function sendEmail(cfg: SmtpConfig, draft: DraftOptions): Promise<string> {
const transport = createTransport(cfg);
try {
const info = await transport.sendMail({
from: draft.from,
to: draft.to,
cc: draft.cc,
subject: draft.subject,
text: draft.body,
inReplyTo: draft.inReplyTo,
references: draft.references,
});
return info.messageId;
} finally {
transport.close();
}
}
src / smtp.ts
import nodemailer from "nodemailer";
export interface SmtpConfig {
host: string;
port: number;
user: string;
password: string;
}
export interface DraftOptions {
from: string;
to: string;
cc?: string;
subject: string;
body: string;
inReplyTo?: string;
references?: string;
}
function createTransport(cfg: SmtpConfig) {
return nodemailer.createTransport({
host: cfg.host,
port: cfg.port,
secure: cfg.port === 465,
auth: { user: cfg.user, pass: cfg.password },
connectionTimeout: 20_000,
greetingTimeout: 20_000,
socketTimeout: 60_000,
});
}
export async function verifySmtpConnection(cfg: SmtpConfig): Promise<void> {
const transport = createTransport(cfg);
try {
await transport.verify();
} finally {
transport.close();
}
}
export async function sendEmail(cfg: SmtpConfig, draft: DraftOptions): Promise<string> {
const transport = createTransport(cfg);
try {
const info = await transport.sendMail({
from: draft.from,
to: draft.to,
cc: draft.cc,
subject: draft.subject,
text: draft.body,
inReplyTo: draft.inReplyTo,
references: draft.references,
});
return info.messageId;
} finally {
transport.close();
}
}