Skip to content

k.mail ​

Outbound SMTP, IMAP inbox collection, raw EML parsing, Amazon SES, anti-spam checking, and Mail module context

Execution ContextPrerequisitesTypical Use
Site API / Code / Jobs; module requires Mail module contextDefault SMTP uses org credits; external SMTP / IMAP / SES need credentialsTransactional 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 ​

js
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 / PropertyDescriptionReturns
createMessage()Create a MailMessage message builderMailMessage
createSmtpServer()Create an external SmtpServer configuration objectSmtpServer
smtpSend messages via the site default channel or external SMTP serverSMTPSender
imapCollect messages and inspect UID ranges from an IMAP inboxImapCollector
utilityParse raw RFC822 EML summaries, full details, and attachmentsMailUtility
amazonsesSend structured or raw MIME emails via AWS SESAmazonses
spamassassinScore messages for spam via local or remote SpamAssassinSpamassassin
moduleKooboo Mail module context (Mail module execution context only)KMailModule

createMessage() / createSmtpServer() ​

MethodParametersReturnsDescription
createMessage()NoneMailMessageCreate a new message builder
createSmtpServer()NoneSmtpServerCreate an external SMTP server configuration object
js
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 ​

FieldDescription
from / to / cc / bcc / replyToEmail address string; separate multiple recipients with commas
subjectMessage subject
htmlBody / textBody / ampBodyHTML body, plain text body, and AMP4Email body
attachmentsAttachment collection
MethodDescription
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:

js
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 commas

When 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() ​

MethodParametersReturnsDescription
smtp.send(message)message: MailMessagevoidSend using the site's default mail channel
smtp.send(server, message)server: SmtpServer, message: MailMessagevoidSend using a specified external SMTP server

Site Default Mail Channel ​

js
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 ​

js
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).

MethodParametersReturnsDescription
collect(setting, start, count)ImapSetting, number, numberMsgRawBody[]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, numberMsgRawBody[]Fetch the latest count messages
get(setting, uid)ImapSetting, numberMsgRawBodyFetch a single message by UID
getRange(setting)ImapSettingIDRangeReturn the mailbox UID range (lowBound, highBound)
js
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 ​

MethodParametersReturnsDescription
parseSummary(msgBody)MsgBody: stringMessageParse summary headers (from, to, subject, hasAttachment, etc.)
parseDetail(msgBody)MsgBody: stringMailDetailViewModelParse full message details (from as AddressModel, html, uTCTime, localTime, attachments)
downloadAttachment(msgBody, fileName)MsgBody: string, FileName: stringnumber[] | nullExtract a named attachment as binary bytes; returns null when no matching attachment is found
js
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.

MethodParametersReturnsDescription
createEmail(setting)AwsMailSetting (accessKeyId, secretAccessKey, region, charset?)AwsEmailCreate an AWS SES client
client.send(mailParam)AwsMailParam (from, to, subject, htmlBody, textBody, sourceArn?)AwsSendEmailResponseSend structured HTML/text email (does not throw on send errors; returns hasError: true and error)
client.sendRaw(msg)MailMessageAwsSendEmailResponseSend 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:

js
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.

EntryParametersReturnsDescription
spamassassin.local-ServerLocal default SpamAssassin server
spamassassin.connect(host, user, port)string, string, numberServerConnect to a remote SpamAssassin instance
MethodResult FieldsDescription
check(mail)spam, score, currentScore, criticalScoreCheck spam classification and scores
report(mail)spam, score, currentScore, criticalScore, bodyCheck spam and return rule breakdown text
ping(){ code: 0, ... }Health check
js
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.

MemberTypeDescription
contextMailModuleContextMail module runtime context
baseUrlstringBase URL for the mail module
configanyModule configuration object
namestringActive mail module name
localDatabaseIDatabaseModule-local IndexedDB store
localSqliteSqliteDatabaseModule-local SQLite store
list()MailModule[]List installed mail modules

TypeScript Definitions ​

Show full TypeScript definitions
ts
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[];
}
  • k.api — Register API endpoints
  • k.request — Read raw request body payloads
  • k.module — Site script module runtime