k.mail
Outbound SMTP, IMAP inbox collection, raw EML parsing, Amazon SES, anti-spam checking, and Mail module context
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
Site API / Code / Jobs; module requires Mail module context | Default SMTP uses org credits; external SMTP / IMAP / SES need credentials | Transactional email sending, inbox EML parsing, spam scoring, mail extensions |
k.mail provides full email capabilities for server-side scripts, covering message building, site default and external SMTP delivery, IMAP inbox retrieval, RFC822 EML parsing, Amazon SES, SpamAssassin checks, and Kooboo Mail module context.
Quick Start
k.api.post("send-notice", () => {
const msg = k.mail.createMessage()
msg.from = "noreply@your-domain.com"
msg.to = k.request.form.email
msg.subject = "Welcome"
msg.htmlBody = "<p>Thanks for signing up.</p>"
k.mail.smtp.send(msg)
return { sent: true, previewEmlLength: msg.toEml().length }
})Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
createMessage() | Create a MailMessage message builder | MailMessage |
createSmtpServer() | Create an external SmtpServer configuration object | SmtpServer |
smtp | Send messages via the site default channel or external SMTP server | SMTPSender |
imap | Collect messages and inspect UID ranges from an IMAP inbox | ImapCollector |
utility | Parse raw RFC822 EML summaries, full details, and attachments | MailUtility |
amazonses | Send structured or raw MIME emails via AWS SES | Amazonses |
spamassassin | Score messages for spam via local or remote SpamAssassin | Spamassassin |
module | Kooboo Mail module context (Mail module execution context only) | KMailModule |
createMessage() / createSmtpServer()
| Method | Parameters | Returns | Description |
|---|---|---|---|
createMessage() | None | MailMessage | Create a new message builder |
createSmtpServer() | None | SmtpServer | Create an external SMTP server configuration object |
const msg = k.mail.createMessage()
msg.from = "sender@example.com"
msg.to = "user@example.com"
msg.subject = "Hello"
msg.htmlBody = "<p>HTML body</p>"
msg.textBody = "Plain text"
msg.ampBody = "<html amp4email><body>AMP body</body></html>"
const server = k.mail.createSmtpServer()
server.host = "smtp.example.com"
server.port = 465
server.ssl = true
server.username = "sender@example.com"
server.password = "your-password"MailMessage Fields and Methods
| Field | Description |
|---|---|
from / to / cc / bcc / replyTo | Email address string; separate multiple recipients with commas |
subject | Message subject |
htmlBody / textBody / ampBody | HTML body, plain text body, and AMP4Email body |
attachments | Attachment collection |
| Method | Description |
|---|---|
addAttachment(FullFileNameOrUrl) | Attach an http:// or https:// URL (or an absolute server filesystem path); does not resolve Kooboo site-relative paths (silently skipped). For site files, read bytes via k.file.readBinary(...) and pass them to addAttachment(filename, BinaryBytes) |
addAttachment(filename, BinaryBytes) | Attach raw binary bytes |
attachObject(filename, obj) | Does not serialize JS objects to JSON: only attaches when obj is byte[] (binary attachment) or null (loads filename as path/URL), and silently ignores other objects. To attach JSON, serialize to bytes first and pass to addAttachment(filename, BinaryBytes) |
toEml() | Export the complete RFC822 EML string |
Multiple Recipients
to, cc, bcc, from, and replyTo accept comma-separated recipient lists as well as RFC 5322 display names:
msg.to = "alice@example.com,bob@example.com"
msg.to = "Alice <alice@example.com>, Bob <bob@example.com>"
msg.cc = "carol@example.com; dave@example.com" // "; " is normalized to commasWhen using the site's default sender k.mail.smtp.send(msg), organization email credits are deducted per parsed recipient address; external SMTP via k.mail.smtp.send(server, msg) relays MIME To/Cc/Bcc directly via MailKit.
smtp.send()
| Method | Parameters | Returns | Description |
|---|---|---|---|
smtp.send(message) | message: MailMessage | void | Send using the site's default mail channel |
smtp.send(server, message) | server: SmtpServer, message: MailMessage | void | Send using a specified external SMTP server |
Site Default Mail Channel
k.api.post(() => {
const msg = k.mail.createMessage()
msg.from = "noreply@your-domain.com"
msg.to = k.request.form.email
msg.subject = "Notification"
msg.htmlBody = "<p>Thanks for signing up.</p>"
k.mail.smtp.send(msg)
return { sent: true }
})Sending via the default channel is gated by organization email quota and throws errors such as No enough email sending credits if depleted.
External SMTP Server
k.api.post(() => {
const msg = k.mail.createMessage()
msg.from = "sender@qq.com"
msg.to = k.request.form.to
msg.subject = "Test"
msg.htmlBody = "<div>Content</div>"
const server = k.mail.createSmtpServer()
server.host = "smtp.qq.com"
server.port = 465
server.ssl = true
server.username = "sender@qq.com"
server.password = k.request.form.smtpPassword
k.mail.smtp.send(server, msg)
return { sent: true }
})imap
Fetch messages from an IMAP Inbox using an ImapSetting object (emailAddress, password, host, forceSSL, port).
| Method | Parameters | Returns | Description |
|---|---|---|---|
collect(setting, start, count) | ImapSetting, number, number | MsgRawBody[] | Fetch up to count messages with uID > start using start as an exclusive lower-bound IMAP UID cursor (pass 0 to start from UID 1, or pass the last fetched message's uID for incremental polling), not a 0/1-based message index |
collectLatestMails(setting, count) | ImapSetting, number | MsgRawBody[] | Fetch the latest count messages |
get(setting, uid) | ImapSetting, number | MsgRawBody | Fetch a single message by UID |
getRange(setting) | ImapSetting | IDRange | Return the mailbox UID range (lowBound, highBound) |
k.api.post(() => {
const setting = {
emailAddress: k.request.form.email,
host: k.request.form.host,
forceSSL: true,
port: 993,
password: k.request.form.password
}
const list = k.mail.imap.collectLatestMails(setting, 5)
const first = list[0]
const detail = first ? k.mail.utility.parseDetail(first.rawBody) : null
return {
count: list.length,
subject: detail?.subject
}
})Each MsgRawBody item contains uID and rawBody (raw RFC822 message text).
utility
| Method | Parameters | Returns | Description |
|---|---|---|---|
parseSummary(msgBody) | MsgBody: string | Message | Parse summary headers (from, to, subject, hasAttachment, etc.) |
parseDetail(msgBody) | MsgBody: string | MailDetailViewModel | Parse full message details (from as AddressModel, html, uTCTime, localTime, attachments) |
downloadAttachment(msgBody, fileName) | MsgBody: string, FileName: string | number[] | null | Extract a named attachment as binary bytes; returns null when no matching attachment is found |
k.api.post(() => {
const { raw } = JSON.parse(k.request.body || "{}")
const detail = k.mail.utility.parseDetail(raw)
return {
subject: detail.subject,
fromName: detail.from?.name,
fromAddress: detail.from?.address,
html: detail.html,
attachmentCount: detail.attachments?.length ?? 0
}
})amazonses
Send email via AWS SES using structured parameters or a raw MailMessage.
| Method | Parameters | Returns | Description |
|---|---|---|---|
createEmail(setting) | AwsMailSetting (accessKeyId, secretAccessKey, region, charset?) | AwsEmail | Create an AWS SES client |
client.send(mailParam) | AwsMailParam (from, to, subject, htmlBody, textBody, sourceArn?) | AwsSendEmailResponse | Send structured HTML/text email (does not throw on send errors; returns hasError: true and error) |
client.sendRaw(msg) | MailMessage | AwsSendEmailResponse | Send a complete raw MIME MailMessage (including attachments and ampBody; does not throw on send errors; returns hasError: true and error) |
client.send() and client.sendRaw() return AwsSendEmailResponse (extending SendEmailResponse with hasError: boolean and error: string | null) and catch exceptions internally instead of throwing; always check res.hasError:
const client = k.mail.amazonses.createEmail({
accessKeyId: "...",
secretAccessKey: "...",
region: "EUCentral1",
charset: "UTF-8"
})
const res = client.send({
from: "me@example.com",
to: ["user@example.com"],
subject: "Subject",
htmlBody: "<p>HTML</p>",
textBody: "Text",
sourceArn: ""
})
if (res.hasError) {
throw new Error(res.error || "AWS SES send failed")
}spamassassin
Check emails for spam using SpamAssassin.
| Entry | Parameters | Returns | Description |
|---|---|---|---|
spamassassin.local | - | Server | Local default SpamAssassin server |
spamassassin.connect(host, user, port) | string, string, number | Server | Connect to a remote SpamAssassin instance |
| Method | Result Fields | Description |
|---|---|---|
check(mail) | spam, score, currentScore, criticalScore | Check spam classification and scores |
report(mail) | spam, score, currentScore, criticalScore, body | Check spam and return rule breakdown text |
ping() | { code: 0, ... } | Health check |
k.api.post(() => {
const { raw } = JSON.parse(k.request.body || "{}")
const rsp = k.mail.spamassassin.local.check(raw)
return {
spam: rsp.spam,
score: rsp.score,
currentScore: rsp.currentScore,
criticalScore: rsp.criticalScore
}
})module
k.mail.module is available only inside the Kooboo Mail module execution context (analogous to k.module). Accessing it from normal site API scripts throws an exception.
| Member | Type | Description |
|---|---|---|
context | MailModuleContext | Mail module runtime context |
baseUrl | string | Base URL for the mail module |
config | any | Module configuration object |
name | string | Active mail module name |
localDatabase | IDatabase | Module-local IndexedDB store |
localSqlite | SqliteDatabase | Module-local SQLite store |
list() | MailModule[] | List installed mail modules |
TypeScript Definitions
Show full TypeScript definitions
interface Mail {
utility: MailUtility;
smtp: SMTPSender;
imap: ImapCollector;
amazonses: Amazonses;
spamassassin: Spamassassin;
module: KMailModule;
createMessage(): MailMessage;
createSmtpServer(): SmtpServer;
}
interface MailMessage {
to: string;
replyTo: string;
cc: string;
bcc: string;
from: string;
subject: string;
textBody: string;
htmlBody: string;
ampBody: string;
attachments: any;
addAttachment(FullFileNameOrUrl: string): void;
addAttachment(filename: string, BinaryBytes: number[]): void;
attachObject(filename: string, obj: any): void;
toEml(): string;
}
interface SmtpServer {
host: string;
ssl: boolean;
username: string;
password: string;
port: number;
}
interface MailUtility {
parseSummary(MsgBody: string): Message;
parseDetail(MsgBody: string): MailDetailViewModel;
downloadAttachment(MsgBody: string, FileName: string): number[] | null;
}
interface MailDetailViewModel {
messageId: string;
subject: string;
from: AddressModel;
to: AddressModel[];
cc: AddressModel[];
bcc: AddressModel[];
attachments: AttachmentViewModel[];
html: string;
date: Date;
uTCTime: Date;
localTime: Date;
}
interface AddressModel {
name: string;
address: string;
}
interface AttachmentViewModel {
contentType: string;
fileName: string;
type: string;
subType: string;
size: number;
}
interface ImapSetting {
emailAddress: string;
password: string;
host: string;
forceSSL: boolean;
port: number;
}
interface MsgRawBody {
uID: number;
rawBody: string;
}
interface IDRange {
lowBound: number;
highBound: number;
}
interface AwsMailSetting {
accessKeyId: string;
secretAccessKey: string;
region: string;
charset: string;
}
interface AwsMailParam {
from: string;
to: string[];
subject: string;
htmlBody: string;
textBody: string;
sourceArn: string;
}
interface AwsSendEmailResponse {
hasError: boolean;
error: string | null;
messageId?: string;
httpStatusCode?: number;
contentLength?: number;
responseMetadata?: any;
}
interface Spamassassin {
local: Server;
connect(host: string, user: string, port: number): Server;
}
interface Server {
check(mail: string): any;
report(mail: string): any;
ping(): any;
}
interface KMailModule {
context: any;
baseUrl: string;
config: any;
name: string;
localDatabase: IDatabase;
localSqlite: SqliteDatabase;
list(): any[];
}