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
Functions
Section titled “Functions”sendMail()
Section titled “sendMail()”sendMail(config: MailConfiguration, mail: SendMailOptions): Promise<SMTPTransport.SentMessageInfo>Sends one email over SMTP and closes the connection afterwards.
| Parameter | Type | Description |
|---|---|---|
config | MailConfiguration | SMTP server, authentication and sending rules. |
mail | SendMailOptions | The 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
| Field | Type | Required | Description |
|---|---|---|---|
location | string | Yes | Host name of the mail server. Used for SMTP when smtpLocation is empty. |
smtpLocation | string | No | Host name of the SMTP server, if it differs from location. |
port | number | Yes | Port, used for SMTP when smtpPort is null or undefined. |
smtpPort | number | No | SMTP port. If the resulting port is 0, port 465 is used. |
userName | string | Yes | User name for authentication. |
password | string | No | Password. Give either a password or the OAuth2 fields, not both. |
secure | boolean | No | true 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. |
useTestAccount | boolean | No | Has no effect. |
defaultFrom | string | No | Sender used when a message has no from, for example Name <name@example.com>. |
isSendToMockRecipientsEnabled | boolean | No | If 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. |
mockRecipientAddresses | string | No | Comma-separated recipients used when isSendToMockRecipientsEnabled is true. |
extraOptions | Partial<SMTPTransport.Options> | No | Further Nodemailer SMTP transport options, which override the ones Lowgile sets. |
oauthClientId | string | No | Client ID of an app registration, for OAuth2 client credentials authentication. |
oauthClientSecret | string | No | Client secret for OAuth2. |
oauthTenantId | string | No | Microsoft Entra tenant ID. Used to build the authority URL https://login.microsoftonline.com/<tenant> when oauthAuthorityUrl is empty. |
oauthAuthorityUrl | string | No | Authority URL for OAuth2. Either this or oauthTenantId is required for OAuth2. |
oauthScopes | string[] | string | No | Scopes 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()
Section titled “sendMails()”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().
| Parameter | Type | Description |
|---|---|---|
config | MailConfiguration | SMTP server, authentication and sending rules. See sendMail(). |
mails | SendMailOptions[] | The messages. |
Returns: Promise<SMTPTransport.SentMessageInfo[]>, one result per message, in order. The promise rejects if any message fails. · Availability: Server
createDraftMailAsEmlFile()
Section titled “createDraftMailAsEmlFile()”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.
| Parameter | Type | Description |
|---|---|---|
mail | SendMailOptions | The message, as for sendMail(). |
config.defaultFrom | string | Sender used when the message has no from. |
Returns: Promise<Buffer>, the .eml file content · Availability: Server
openImapClient()
Section titled “openImapClient()”openImapClient(config: ImapConfig): SimpleImapCreates an IMAP client for a mailbox. The connection is opened on first use, for example by openFolder().
| Parameter | Type | Description |
|---|---|---|
config | ImapConfig | IMAP server and authentication. |
ImapConfig fields
| Field | Type | Required | Description |
|---|---|---|---|
location | string | No | Host name of the IMAP server. host takes precedence. |
host | string | No | Host name of the IMAP server. |
port | number | No | Port. Default: 993. A value of 0 is passed on unchanged. |
userName | string | No | User name. user takes precedence. |
user | string | No | User name. |
password | string | No | Password. Give either a password or the OAuth2 fields, not both. |
tls | boolean | No | Uses TLS from the start of the connection. Default: true. |
autotls | string | No | When to upgrade a plain connection with STARTTLS. Default: always. |
tlsOptions | ConnectionOptions | No | Node.js TLS options. Lowgile sets servername to the host name. |
connTimeout | number | No | Connection timeout in milliseconds. |
authTimeout | number | No | Authentication timeout in milliseconds. |
keepalive | any | No | Keeps the connection alive while idle. If set, Lowgile also reconnects after the connection closes and reopens the last folder. |
debug | (info: string) => void | No | Receives node-imap debug output. |
autoExpungeOnClose | boolean | No | If true, close() permanently removes the messages flagged as deleted in the open folder. |
extraOptions | Partial<Imap.Config> | No | Further node-imap options, applied last. |
oauthClientId, oauthClientSecret, oauthTenantId, oauthAuthorityUrl, oauthScopes | string | No | OAuth2 client credentials, as for sendMail(). |
Returns: SimpleImap · Availability: Server
Classes
Section titled “Classes”SimpleImap
Section titled “SimpleImap”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()}newMails$
Section titled “newMails$”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()
Section titled “openFolder()”openFolder(folderName: string): Promise<Imap.Box>Connects if necessary and opens a folder, such as INBOX. Later calls work on this folder.
| Parameter | Type | Description |
|---|---|---|
folderName | string | Full name of the folder. |
Returns: Promise<Imap.Box>, the folder’s status, including message counts · Availability: Server
findMessageIds()
Section titled “findMessageIds()”findMessageIds(criteria: MailSearchCriteria): Promise<number[]>Searches the open folder and returns the UIDs of the matching messages, without loading them.
| Parameter | Type | Description |
|---|---|---|
criteria | MailSearchCriteria | Search criteria, combined with AND. |
Returns: Promise<number[]> · Availability: Server
findMessages()
Section titled “findMessages()”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.
| Parameter | Type | Description |
|---|---|---|
criteria | MailSearchCriteria | Search criteria, combined with AND. |
options | FetchOptions | What to fetch. |
FetchOptions fields
| Field | Type | Required | Description |
|---|---|---|---|
markSeen | boolean | No | Marks the messages as read. Default: false. |
struct | boolean | No | Also fetches the message structure. |
envelope | boolean | No | Also fetches the message envelope. |
size | boolean | No | Also fetches the message size. |
modifiers | object | No | Fetch modifiers of IMAP extensions. |
Returns: Promise<Mail[]> · Availability: Server
findAndStreamMessages()
Section titled “findAndStreamMessages()”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.
| Parameter | Type | Description |
|---|---|---|
criteria | MailSearchCriteria | Search criteria, combined with AND. |
scope.includeExisting | boolean | Emits the messages that already match. |
scope.includeIncoming | boolean | Keeps the observable open and emits new matching messages as they arrive. Otherwise it completes once the existing messages are emitted. |
options | FetchOptions | What to fetch. See findMessages(). |
Returns: Observable<Mail> (RxJS) · Availability: Server
getMessagesByIds()
Section titled “getMessagesByIds()”getMessagesByIds(ids: number[], options?: FetchOptions): Promise<Mail[]>Loads messages of the open folder by UID.
| Parameter | Type | Description |
|---|---|---|
ids | number[] | Message UIDs. |
options | FetchOptions | What to fetch. See findMessages(). |
Returns: Promise<Mail[]> · Availability: Server
getMessageById()
Section titled “getMessageById()”getMessageById(id: number, options?: FetchOptions): Promise<Mail>Loads one message of the open folder by UID.
| Parameter | Type | Description |
|---|---|---|
id | number | Message UID. |
options | FetchOptions | What to fetch. See findMessages(). |
Returns: Promise<Mail>, undefined if there is no such message · Availability: Server
setSeen()
Section titled “setSeen()”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.
| Parameter | Type | Description |
|---|---|---|
messageUids | MailUidsOrRangesOrMails | The messages: UIDs, UID ranges, Mail objects, or a list of these. |
seen | boolean | true sets the flag, false removes it. Default: true. |
Returns: Promise<void> · Availability: Server
setAnswered()
Section titled “setAnswered()”setAnswered(messageUids: MailUidsOrRangesOrMails, answered?: boolean): Promise<void>Sets or removes the Answered flag. See setSeen().
Returns: Promise<void> · Availability: Server
setDraft()
Section titled “setDraft()”setDraft(messageUids: MailUidsOrRangesOrMails, draft?: boolean): Promise<void>Sets or removes the Draft flag. See setSeen().
Returns: Promise<void> · Availability: Server
setDeleted()
Section titled “setDeleted()”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()
Section titled “setFlagged()”setFlagged(messageUids: MailUidsOrRangesOrMails, flagged?: boolean): Promise<void>Sets or removes the Flagged flag. See setSeen().
Returns: Promise<void> · Availability: Server
isSeen()
Section titled “isSeen()”isSeen(mail: Mail): booleanChecks whether a loaded message has the Seen flag. isAnswered(), isDraft(), isDeleted() and isFlagged() check the other flags.
| Parameter | Type | Description |
|---|---|---|
mail | Mail | A message loaded by this client. |
Returns: boolean · Availability: Server
isAnswered()
Section titled “isAnswered()”isAnswered(mail: Mail): booleanChecks whether a loaded message has the Answered flag.
Returns: boolean · Availability: Server
isDraft()
Section titled “isDraft()”isDraft(mail: Mail): booleanChecks whether a loaded message has the Draft flag.
Returns: boolean · Availability: Server
isDeleted()
Section titled “isDeleted()”isDeleted(mail: Mail): booleanChecks whether a loaded message has the Deleted flag.
Returns: boolean · Availability: Server
isFlagged()
Section titled “isFlagged()”isFlagged(mail: Mail): booleanChecks whether a loaded message has the Flagged flag.
Returns: boolean · Availability: Server
replaceInlineAttachmentsInHtml()
Section titled “replaceInlineAttachmentsInHtml()”replaceInlineAttachmentsInHtml(mail: Mail): MailReturns 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.
| Parameter | Type | Description |
|---|---|---|
mail | Mail | A loaded message. |
Returns: Mail · Availability: Server
copy()
Section titled “copy()”copy(messageUids: MailUidsOrRangesOrMails, targetFolder: string): Promise<void>Copies messages from the open folder to another folder.
| Parameter | Type | Description |
|---|---|---|
messageUids | MailUidsOrRangesOrMails | The messages. |
targetFolder | string | Full name of the target folder. |
Returns: Promise<void> · Availability: Server
move()
Section titled “move()”move(messageUids: MailUidsOrRangesOrMails, targetFolder: string): Promise<void>Moves messages from the open folder to another folder. The moved messages get new UIDs.
| Parameter | Type | Description |
|---|---|---|
messageUids | MailUidsOrRangesOrMails | The messages. |
targetFolder | string | Full name of the target folder. |
Returns: Promise<void> · Availability: Server
expunge()
Section titled “expunge()”expunge(): Promise<void>Permanently removes the messages flagged as deleted in the open folder.
Returns: Promise<void> · Availability: Server
getFolderList()
Section titled “getFolderList()”getFolderList(nsPrefix?: string, isNested?: boolean): Promise<Folder[]>Connects if necessary and lists the folders of the mailbox.
| Parameter | Type | Description |
|---|---|---|
nsPrefix | string | Namespace prefix to list. Default: ''. |
isNested | boolean | If true, subfolders are included in children. Default: false. |
Returns: Promise<Folder[]> · Availability: Server
getFolderNames()
Section titled “getFolderNames()”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.
| Parameter | Type | Description |
|---|---|---|
nsPrefix | string | Namespace prefix to list. Default: ''. |
isNested | boolean | Includes subfolders. Default: false. |
Returns: Promise<string[]> · Availability: Server
newFolder()
Section titled “newFolder()”newFolder(folderName: string): Promise<void>Creates a folder.
| Parameter | Type | Description |
|---|---|---|
folderName | string | Full 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()
Section titled “deleteFolder()”deleteFolder(folderName: string): Promise<void>Deletes a folder.
| Parameter | Type | Description |
|---|---|---|
folderName | string | Full name of the folder. |
Returns: Promise<void> · Availability: Server
renameFolder()
Section titled “renameFolder()”renameFolder(oldFolderName: string, newFolderName: string): Promise<void>Renames a folder.
| Parameter | Type | Description |
|---|---|---|
oldFolderName | string | Current full name. |
newFolderName | string | New full name. |
Returns: Promise<void> · Availability: Server
subscribeFolder()
Section titled “subscribeFolder()”subscribeFolder(folderName: string): Promise<void>Subscribes to a folder on the server.
| Parameter | Type | Description |
|---|---|---|
folderName | string | Full name of the folder. |
Returns: Promise<void> · Availability: Server
close()
Section titled “close()”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>.
MailSearchCriteria
Section titled “MailSearchCriteria”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
MailUidsOrRangesOrMails
Section titled “MailUidsOrRangesOrMails”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
FindAndStreamScope
Section titled “FindAndStreamScope”interface FindAndStreamScope { includeExisting: boolean includeIncoming: boolean}Which messages findAndStreamMessages() emits. See there.
Availability: Server
Folder
Section titled “Folder”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,headersand more) - the IMAP attributes
uid,flags,dateandsize sequenceNumber, the message’s sequence number in the foldermailType:'mail','readReceipt'or'nonDeliveryReport', andstatusCode, the delivery status code of a non-delivery reportgetVisibleText()andgetFragments(), which split the text body into the new reply and quoted or signature partsgetHtmlWithHeaders(), 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
Related
Section titled “Related”- Service Integration API
- Configuration items
- Send emails from your app
- Process incoming emails
- Sys API overview