Skip to content

Sys.Mail

Sys.Mail sends emails over SMTP, creates unsent draft messages as .eml files, and opens IMAP connections to read and organize mailboxes, all in server-side code. Sending uses Nodemailer (npm package nodemailer, version ^8.0.1), reading uses node-imap (version ^0.9.6).

The connection settings usually come from a configuration item of the type Mail server connection, read as This.$Config.<ItemName>, which has the fields of MailConfiguration. A Mail Service Integration wraps sendMail() and sendMails() with its configuration item already filled in.

Availability: Server

sendMail(config: MailConfiguration, mail: SendMailOptions): Promise<SMTPTransport.SentMessageInfo>

Sends one email over SMTP and closes the connection afterwards.

ParameterTypeDescription
configMailConfigurationSMTP server, authentication and sending rules.
mailSendMailOptionsThe message: Nodemailer’s message options, such as from, to, cc, bcc, subject, text, html and attachments. If from is missing, config.defaultFrom is used.

MailConfiguration fields

FieldTypeRequiredDescription
locationstringYesHost name of the mail server. Used for SMTP when smtpLocation is empty.
smtpLocationstringNoHost name of the SMTP server, if it differs from location.
portnumberYesPort, used for SMTP when smtpPort is null or undefined.
smtpPortnumberNoSMTP port. If the resulting port is 0, port 465 is used.
userNamestringYesUser name for authentication.
passwordstringNoPassword. Give either a password or the OAuth2 fields, not both.
securebooleanNotrue uses TLS from the start of the connection, false upgrades the connection with STARTTLS. TLS is required either way. Default: false for port 587, otherwise true.
useTestAccountbooleanNoHas no effect.
defaultFromstringNoSender used when a message has no from, for example Name <name@example.com>.
isSendToMockRecipientsEnabledbooleanNoIf true, messages go only to mockRecipientAddresses: CC and BCC are removed, and a line naming the real recipients is added at the top of the text and HTML body.
mockRecipientAddressesstringNoComma-separated recipients used when isSendToMockRecipientsEnabled is true.
extraOptionsPartial<SMTPTransport.Options>NoFurther Nodemailer SMTP transport options, which override the ones Lowgile sets.
oauthClientIdstringNoClient ID of an app registration, for OAuth2 client credentials authentication.
oauthClientSecretstringNoClient secret for OAuth2.
oauthTenantIdstringNoMicrosoft Entra tenant ID. Used to build the authority URL https://login.microsoftonline.com/<tenant> when oauthAuthorityUrl is empty.
oauthAuthorityUrlstringNoAuthority URL for OAuth2. Either this or oauthTenantId is required for OAuth2.
oauthScopesstring[] | stringNoScopes to request. Default: https://outlook.office.com/.default.

Returns: Promise<SMTPTransport.SentMessageInfo>, Nodemailer’s delivery result with messageId, accepted, rejected and response · Availability: Server

const info = await Sys.Mail.sendMail(This.$Config.MailServer, {
to: 'customer@example.com',
subject: 'Your order has shipped',
html: '<p>Your order <b>A-1042</b> is on its way.</p>',
attachments: [{ filename: 'invoice.pdf', content: invoicePdfBuffer }],
})

Lowgile throws an error when neither a password nor complete OAuth2 settings (client ID, client secret, and tenant ID or authority URL) are given, or when both are. OAuth2 access tokens are cached and renewed shortly before they expire. The SMTP host name is resolved to an IPv4 address first, to avoid long delays on servers where IPv6 sending fails.

Note

A Mail server connection configuration item sets smtpPort to 0 by default, which selects port 465, not the value of port. It also enables isSendToMockRecipientsEnabled by default, so messages only reach real recipients after you turn it off.

sendMails(config: MailConfiguration, mails: SendMailOptions[]): Promise<SMTPTransport.SentMessageInfo[]>

Sends several emails over one SMTP connection, in parallel, and closes the connection afterwards. The configuration and message options are the same as for sendMail().

ParameterTypeDescription
configMailConfigurationSMTP server, authentication and sending rules. See sendMail().
mailsSendMailOptions[]The messages.

Returns: Promise<SMTPTransport.SentMessageInfo[]>, one result per message, in order. The promise rejects if any message fails. · Availability: Server

createDraftMailAsEmlFile(mail: SendMailOptions, config?: { defaultFrom?: string }): Promise<Buffer<ArrayBufferLike>>

Builds a message as the content of an .eml file without sending it. The message carries the header X-Unsent: 1, so mail clients such as Outlook open it as a draft the End user can edit and send.

ParameterTypeDescription
mailSendMailOptionsThe message, as for sendMail().
config.defaultFromstringSender used when the message has no from.

Returns: Promise<Buffer>, the .eml file content · Availability: Server

openImapClient(config: ImapConfig): SimpleImap

Creates an IMAP client for a mailbox. The connection is opened on first use, for example by openFolder().

ParameterTypeDescription
configImapConfigIMAP server and authentication.

ImapConfig fields

FieldTypeRequiredDescription
locationstringNoHost name of the IMAP server. host takes precedence.
hoststringNoHost name of the IMAP server.
portnumberNoPort. Default: 993. A value of 0 is passed on unchanged.
userNamestringNoUser name. user takes precedence.
userstringNoUser name.
passwordstringNoPassword. Give either a password or the OAuth2 fields, not both.
tlsbooleanNoUses TLS from the start of the connection. Default: true.
autotlsstringNoWhen to upgrade a plain connection with STARTTLS. Default: always.
tlsOptionsConnectionOptionsNoNode.js TLS options. Lowgile sets servername to the host name.
connTimeoutnumberNoConnection timeout in milliseconds.
authTimeoutnumberNoAuthentication timeout in milliseconds.
keepaliveanyNoKeeps the connection alive while idle. If set, Lowgile also reconnects after the connection closes and reopens the last folder.
debug(info: string) => voidNoReceives node-imap debug output.
autoExpungeOnClosebooleanNoIf true, close() permanently removes the messages flagged as deleted in the open folder.
extraOptionsPartial<Imap.Config>NoFurther node-imap options, applied last.
oauthClientId, oauthClientSecret, oauthTenantId, oauthAuthorityUrl, oauthScopesstringNoOAuth2 client credentials, as for sendMail().

Returns: SimpleImap · Availability: Server

An IMAP connection to one mailbox, returned by openImapClient(). Open a folder with openFolder() before searching, reading or changing messages, and call close() when done. Message IDs are IMAP UIDs.

const imap = Sys.Mail.openImapClient(This.$Config.MailServer)
try {
await imap.openFolder('INBOX')
const mails = await imap.findMessages(['UNSEEN', ['SINCE', new Date('2026-01-01')]])
for (const mail of mails) {
Sys.Log.info(mail.subject, mail.from?.text)
}
await imap.setSeen(mails)
} finally {
await imap.close()
}
readonly newMails$: Observable<number>

Emits the number of new messages whenever the server reports new mail in the open folder.

Type: Observable<number> (RxJS) · Availability: Server

openFolder(folderName: string): Promise<Imap.Box>

Connects if necessary and opens a folder, such as INBOX. Later calls work on this folder.

ParameterTypeDescription
folderNamestringFull name of the folder.

Returns: Promise<Imap.Box>, the folder’s status, including message counts · Availability: Server

findMessageIds(criteria: MailSearchCriteria): Promise<number[]>

Searches the open folder and returns the UIDs of the matching messages, without loading them.

ParameterTypeDescription
criteriaMailSearchCriteriaSearch criteria, combined with AND.

Returns: Promise<number[]> · Availability: Server

findMessages(criteria: MailSearchCriteria, options?: FetchOptions): Promise<Mail[]>

Searches the open folder and loads the matching messages. Messages are not marked as read unless options.markSeen is true.

ParameterTypeDescription
criteriaMailSearchCriteriaSearch criteria, combined with AND.
optionsFetchOptionsWhat to fetch.

FetchOptions fields

FieldTypeRequiredDescription
markSeenbooleanNoMarks the messages as read. Default: false.
structbooleanNoAlso fetches the message structure.
envelopebooleanNoAlso fetches the message envelope.
sizebooleanNoAlso fetches the message size.
modifiersobjectNoFetch modifiers of IMAP extensions.

Returns: Promise<Mail[]> · Availability: Server

findAndStreamMessages(criteria: MailSearchCriteria, scope: FindAndStreamScope, options?: FetchOptions): Observable<Mail>

Emits matching messages one by one as they are loaded, and optionally keeps watching the folder for new matching messages.

ParameterTypeDescription
criteriaMailSearchCriteriaSearch criteria, combined with AND.
scope.includeExistingbooleanEmits the messages that already match.
scope.includeIncomingbooleanKeeps the observable open and emits new matching messages as they arrive. Otherwise it completes once the existing messages are emitted.
optionsFetchOptionsWhat to fetch. See findMessages().

Returns: Observable<Mail> (RxJS) · Availability: Server

getMessagesByIds(ids: number[], options?: FetchOptions): Promise<Mail[]>

Loads messages of the open folder by UID.

ParameterTypeDescription
idsnumber[]Message UIDs.
optionsFetchOptionsWhat to fetch. See findMessages().

Returns: Promise<Mail[]> · Availability: Server

getMessageById(id: number, options?: FetchOptions): Promise<Mail>

Loads one message of the open folder by UID.

ParameterTypeDescription
idnumberMessage UID.
optionsFetchOptionsWhat to fetch. See findMessages().

Returns: Promise<Mail>, undefined if there is no such message · Availability: Server

setSeen(messageUids: MailUidsOrRangesOrMails, seen?: boolean): Promise<void>

Sets or removes the Seen (read) flag of messages in the open folder. setAnswered(), setDraft(), setDeleted() and setFlagged() work the same way for the Answered, Draft, Deleted and Flagged flags.

ParameterTypeDescription
messageUidsMailUidsOrRangesOrMailsThe messages: UIDs, UID ranges, Mail objects, or a list of these.
seenbooleantrue sets the flag, false removes it. Default: true.

Returns: Promise<void> · Availability: Server

setAnswered(messageUids: MailUidsOrRangesOrMails, answered?: boolean): Promise<void>

Sets or removes the Answered flag. See setSeen().

Returns: Promise<void> · Availability: Server

setDraft(messageUids: MailUidsOrRangesOrMails, draft?: boolean): Promise<void>

Sets or removes the Draft flag. See setSeen().

Returns: Promise<void> · Availability: Server

setDeleted(messageUids: MailUidsOrRangesOrMails, deleted?: boolean): Promise<void>

Sets or removes the Deleted flag. The messages are only removed by expunge(), or by close() with autoExpungeOnClose. See setSeen().

Returns: Promise<void> · Availability: Server

setFlagged(messageUids: MailUidsOrRangesOrMails, flagged?: boolean): Promise<void>

Sets or removes the Flagged flag. See setSeen().

Returns: Promise<void> · Availability: Server

isSeen(mail: Mail): boolean

Checks whether a loaded message has the Seen flag. isAnswered(), isDraft(), isDeleted() and isFlagged() check the other flags.

ParameterTypeDescription
mailMailA message loaded by this client.

Returns: boolean · Availability: Server

isAnswered(mail: Mail): boolean

Checks whether a loaded message has the Answered flag.

Returns: boolean · Availability: Server

isDraft(mail: Mail): boolean

Checks whether a loaded message has the Draft flag.

Returns: boolean · Availability: Server

isDeleted(mail: Mail): boolean

Checks whether a loaded message has the Deleted flag.

Returns: boolean · Availability: Server

isFlagged(mail: Mail): boolean

Checks whether a loaded message has the Flagged flag.

Returns: boolean · Availability: Server

replaceInlineAttachmentsInHtml(mail: Mail): Mail

Returns a copy of the message whose HTML embeds its inline images as data URLs, replacing the cid: references, so the HTML can be shown on its own.

ParameterTypeDescription
mailMailA loaded message.

Returns: Mail · Availability: Server

copy(messageUids: MailUidsOrRangesOrMails, targetFolder: string): Promise<void>

Copies messages from the open folder to another folder.

ParameterTypeDescription
messageUidsMailUidsOrRangesOrMailsThe messages.
targetFolderstringFull name of the target folder.

Returns: Promise<void> · Availability: Server

move(messageUids: MailUidsOrRangesOrMails, targetFolder: string): Promise<void>

Moves messages from the open folder to another folder. The moved messages get new UIDs.

ParameterTypeDescription
messageUidsMailUidsOrRangesOrMailsThe messages.
targetFolderstringFull name of the target folder.

Returns: Promise<void> · Availability: Server

expunge(): Promise<void>

Permanently removes the messages flagged as deleted in the open folder.

Returns: Promise<void> · Availability: Server

getFolderList(nsPrefix?: string, isNested?: boolean): Promise<Folder[]>

Connects if necessary and lists the folders of the mailbox.

ParameterTypeDescription
nsPrefixstringNamespace prefix to list. Default: ''.
isNestedbooleanIf true, subfolders are included in children. Default: false.

Returns: Promise<Folder[]> · Availability: Server

getFolderNames(nsPrefix?: string, isNested?: boolean): Promise<string[]>

Lists the folder names. With isNested, subfolders are included as full paths joined with the server’s delimiter, such as INBOX/Invoices.

ParameterTypeDescription
nsPrefixstringNamespace prefix to list. Default: ''.
isNestedbooleanIncludes subfolders. Default: false.

Returns: Promise<string[]> · Availability: Server

newFolder(folderName: string): Promise<void>

Creates a folder.

ParameterTypeDescription
folderNamestringFull name of the new folder.

Returns: Promise<void> · Availability: Server

Note

newFolder(), deleteFolder(), renameFolder() and subscribeFolder() do not open the connection themselves. Call openFolder() or getFolderList() first.

deleteFolder(folderName: string): Promise<void>

Deletes a folder.

ParameterTypeDescription
folderNamestringFull name of the folder.

Returns: Promise<void> · Availability: Server

renameFolder(oldFolderName: string, newFolderName: string): Promise<void>

Renames a folder.

ParameterTypeDescription
oldFolderNamestringCurrent full name.
newFolderNamestringNew full name.

Returns: Promise<void> · Availability: Server

subscribeFolder(folderName: string): Promise<void>

Subscribes to a folder on the server.

ParameterTypeDescription
folderNamestringFull name of the folder.

Returns: Promise<void> · Availability: Server

close(): Promise<void>

Closes the open folder, expunging deleted messages if autoExpungeOnClose is set, and ends the connection.

Returns: Promise<void> · Availability: Server

These types describe parameters and results of the functions above. They are not reachable as Sys.Mail.<TypeName>.

type MailSearchCriteria = [MailSearchCriterion, ...MailSearchCriterion[]]

A non-empty list of IMAP search criteria, all of which must match. A criterion is one of:

  • a flag keyword without argument, such as 'ALL', 'UNSEEN', 'FLAGGED' or 'DELETED'
  • a pair or triple of keyword and value: ['FROM', 'a@example.com'], ['SUBJECT', 'Invoice'], ['HEADER', 'X-Ticket', '42'], ['SINCE', date], ['LARGER', 100000] or ['UID', '100:*']
  • ['OR', criterion, criterion] for alternatives

Put ! before a keyword to negate it, for example '!SEEN' or ['!FROM', 'noreply@example.com'].

Availability: Server

type MailUidsOrRangesOrMails = MailUidOrRangeOrMail | MailUidOrRangeOrMail[]

One message or a list of messages, each given as a UID (42 or '42'), a UID range ('40:45' or '40:*'), or an object with a uid, such as a loaded Mail.

Availability: Server

interface FindAndStreamScope {
includeExisting: boolean
includeIncoming: boolean
}

Which messages findAndStreamMessages() emits. See there.

Availability: Server

interface Folder {
name: string
attributes: string[]
delimiter: string
children: Folder[]
}

A mailbox folder, as returned by getFolderList(). attributes holds the IMAP folder attributes; NOSELECT means the folder cannot be opened.

Availability: Server

A loaded message. It combines:

  • the parsed message from mailparser (subject, from, to, cc, date, messageId, text, html, attachments, headers and more)
  • the IMAP attributes uid, flags, date and size
  • sequenceNumber, the message’s sequence number in the folder
  • mailType: 'mail', 'readReceipt' or 'nonDeliveryReport', and statusCode, the delivery status code of a non-delivery report
  • getVisibleText() and getFragments(), which split the text body into the new reply and quoted or signature parts
  • getHtmlWithHeaders(), which returns the body as HTML with a table of date, sender, recipients and subject above it

The type is available as Sys.Types.Mail.

Availability: Server