infinity.imap4¶
Module: infinity.imap4
The infinity.imap4 namespace contains a client class for accessing IMAP4 email servers. In contrast to the infinity.pop3 module, IMAP4 organizes messages in server-side mailboxes (folders) and keeps them on the server, so you typically select a mailbox first and then operate on the messages it contains.
client¶
Properties:
- allowUnsafeLegacyRenegotiation
- authMode
- encryptMode
- host
- password
- port
- timeout
- useLegacyServerConnect
- username
- verifyServerCertificate
Methods:
You can use the infinity.imap4.client object to access an IMAP4 server and work with the messages stored on it. The first thing you need to do is set the host, port and encryptMode properties to specify how to connect to the server. Then you'll usually need to set the authMode, username and password properties to specify how to authenticate yourself towards the server. You can also set the timeout to limit the time that the client will try to connect to the server.
After setting the properties, you can use the connect() method to establish a connection to the IMAP4 server. Most operations work on a selected mailbox, so you typically call selectMailbox() before retrieving messages with the other methods. Make sure to call the free() method when finished, to release the memory allocated by the client object.
Example:
infinity.loadModule('infinity.imap4');
let myClient = new infinity.imap4.client();
try {
myClient.host = 'imap.gmail.com';
myClient.port = 993;
myClient.encryptMode = infinity.imap4.client.encryptMode.sslTls;
myClient.authMode = infinity.imap4.client.authMode.userPass;
myClient.username = 'youraccount@gmail.com';
myClient.password = 'yourpassword';
myClient.connect();
console.debug(myClient.listMailboxes());
let inbox = myClient.selectMailbox('INBOX');
if (inbox.totalMsgs > 0)
console.debug(myClient.retrieveText(1));
myClient.disconnect();
} finally {
myClient.free();
}
Properties
allowUnsafeLegacyRenegotiation¶
Type: boolean
Allows the deprecated ssl unsafe legacy renegotiation. This should be avoided and the server's ssl version should be fixed, instead. If that is not possible, then this option can be used to let the IMAP4 client establish a connection nonetheless. Default: false.
authMode¶
Type: infinity.imap4.client.authMode
Gets and sets the authorization mode for the IMAP4 client to use, according to infinity.imap4.client.authMode. Default: userPass.
encryptMode¶
Type: infinity.imap4.client.encryptMode
Gets and sets the encryption mode for the IMAP4 client to use according to infinity.imap4.client.encryptMode. Default: none.
With sslTls, the client uses implicit TLS if port is 993, and explicit TLS (STARTTLS) on any other port. The server must offer STARTTLS, otherwise connect() fails (since 3.11; before, the client went on unencrypted and sent the login data in plain text).
host¶
Type: string
Gets and sets the IMAP4 server address to connect to.
password¶
Type: string
Gets and sets the password for authorization.
port¶
Type: number
Gets and sets the communication port of the IMAP4 server. Default: 143.
timeout¶
Type: number
Gets and sets the timeout in milliseconds, used both for connecting and for reading server responses. Default: 5000.
useLegacyServerConnect¶
Type: boolean
Allows deprecated, unsafe ssl connections. This should be avoided and the server's ssl version should be fixed, instead. If that is not possible, then this option can be used to let the IMAP4 client establish a connection nonetheless. Default: false.
username¶
Type: string
Gets and sets the username for authorization.
verifyServerCertificate¶
Type: boolean
This option will turn on ssl certificate validation, which will result in a connection error if the server's ssl certificate is not valid (e.g. self-signed). Default: false.
Methods
constructor()¶
Lets you create an INFINITY.JS IMAP4 client object instance. Doesn't accept parameters.
Signature:
constructor()
Example:
infinity.loadModule('infinity.imap4');
let myClient = new infinity.imap4.client();
closeMailbox()¶
Closes the currently selected mailbox. According to the IMAP4 protocol, all messages that have been marked as deleted in the mailbox are permanently removed (expunged) when the mailbox is closed.
Signature:
closeMailbox(): boolean
Return type: boolean
Example:
myClient.closeMailbox();
connect()¶
Connects to the IMAP4 server and logs in. The initial properties should be set by the time connect() is called.
Signature:
connect(): void
Example:
myClient.connect();
copy()¶
Copies a message from the currently selected mailbox to another mailbox.
Signature:
copy( msgNum: number, mailbox: string ): boolean
Parameters:
-
msgNum:
numberThe number of the message to copy.
-
mailbox:
stringThe name of the destination mailbox.
Return type: boolean
Example:
myClient.copy(1, 'Archive');
count()¶
Returns the number of messages in the currently selected mailbox. You need to selectMailbox() first.
Signature:
count(): number
Return type: number
Example:
let messageCount = myClient.count();
createMailbox()¶
Creates a new mailbox (folder) with the specified name on the server.
Signature:
createMailbox( name: string ): boolean
Parameters:
- name:
stringThe name of the mailbox to create.
Return type: boolean
Example:
myClient.createMailbox('Archive');
delete()¶
Marks one or more messages in the currently selected mailbox for deletion (by setting the \Deleted flag). The messages are not removed until the mailbox is expunged with expunge() or closed with closeMailbox().
Signature:
delete( msgNum: number ): boolean
delete( msgNums: Array<number> ): boolean
Parameters:
- msgNum:
numberorArray<number>The number of the message to mark for deletion, or an array of message numbers.
Return type: boolean
Example:
myClient.delete(1);
myClient.delete([1, 2, 3]);
deleteMailbox()¶
Deletes the specified mailbox (folder) from the server.
Signature:
deleteMailbox( name: string ): boolean
Parameters:
- name:
stringThe name of the mailbox to delete.
Return type: boolean
Example:
myClient.deleteMailbox('Archive');
disconnect()¶
Logs out and closes the connection; the client can connect() again afterwards. If a command failed in a way that leaves the connection out of step (e.g. an unexpected server response), the client resynchronizes it before the next command, or closes it if that is not possible.
Signature:
disconnect(): void
Example:
myClient.disconnect();
examineMailbox()¶
Opens the specified mailbox in read-only mode and returns its status as a infinity.imap4.mailbox object. This works like selectMailbox(), but does not allow changes (e.g. setting flags) to the mailbox.
Signature:
examineMailbox( name: string ): infinity.imap4.mailbox
Parameters:
- name:
stringThe name of the mailbox to examine.
Return type: infinity.imap4.mailbox
Example:
let inbox = myClient.examineMailbox('INBOX');
console.debug(inbox.totalMsgs);
expunge()¶
Permanently removes all messages that have been marked for deletion (with the \Deleted flag) from the currently selected mailbox.
Signature:
expunge(): boolean
Return type: boolean
Example:
myClient.delete(1);
myClient.expunge();
flags()¶
Returns the flags of the specified message in the currently selected (or examined) mailbox. The message is not changed, in particular it is not marked as seen.
Signature:
flags( msgNum: number ): infinity.imap4.messageFlags
Parameters:
- msgNum:
numberThe number of the message.
Return type: infinity.imap4.messageFlags
Example:
if (myClient.flags(1).seen)
console.log('Message 1 has been read');
free()¶
Frees the memory previously occupied by the IMAP4 client object instance.
Signature:
free(): void
Example:
myClient.free();
listMailboxes()¶
Returns a infinity.imap4.mailboxArray with the names of all mailboxes (folders) in the account.
Signature:
listMailboxes(): infinity.imap4.mailboxArray
Return type: infinity.imap4.mailboxArray
Example:
let mailboxes = myClient.listMailboxes();
console.debug(mailboxes[0]);
mailboxSeparator()¶
Returns the character the server uses to separate the levels of the mailbox hierarchy (e.g. . in INBOX.Archive or /), as reported with the last listMailboxes(). Returns an empty string if the server reported no hierarchy. Before the first listMailboxes(), / is returned, so call it after listing the mailboxes.
Signature:
mailboxSeparator(): string
Return type: string
Example:
let names = myClient.listMailboxes();
let separator = myClient.mailboxSeparator();
renameMailbox()¶
Renames a mailbox (folder) on the server.
Signature:
renameMailbox( oldName: string, newName: string ): boolean
Parameters:
-
oldName:
stringThe current name of the mailbox.
-
newName:
stringThe new name of the mailbox.
Return type: boolean
Example:
myClient.renameMailbox('Archive', 'Archive 2024');
retrieve()¶
Retrieves a raw (undecoded) message from the currently selected mailbox and marks it as read (sets the \Seen flag). Without a filename the message is returned as a string, otherwise it is written to the file and nothing is returned. The message is returned as stored on the server (before 3.11 it was in SMTP transfer form: lines starting with . doubled and an additional final line .).
Signature:
retrieve( msgNum: number ): string
retrieve( msgNum: number, filename: string ): void
Parameters:
-
msgNum:
numberThe number of the message to retrieve.
-
filename:
string, optionalIf a filename is specified, then the message will be saved to that file. The filename can be relative (location relative to the folder with the used INFINITY.JS executable file) or an absolute path.
Return type: string or void
Example:
let messageText = myClient.retrieve(1);
myClient.retrieve(1, 'message.eml');
retrievePeek()¶
Retrieves a raw (undecoded) message from the currently selected mailbox without marking it as read (leaves the \Seen flag unchanged). Without a filename the message is returned as a string, otherwise it is written to the file and nothing is returned. Like retrieve(), the message is returned as stored on the server.
Signature:
retrievePeek( msgNum: number ): string
retrievePeek( msgNum: number, filename: string ): void
Parameters:
-
msgNum:
numberThe number of the message to retrieve.
-
filename:
string, optionalIf a filename is specified, then the message will be saved to that file. The filename can be relative (location relative to the folder with the used INFINITY.JS executable file) or an absolute path.
Return type: string or void
Example:
let messageText = myClient.retrievePeek(1);
retrieveText()¶
Retrieves only the body of the specified message (everything after the header, IMAP BODY[TEXT]) from the currently selected mailbox. The body is returned as sent by the server, i.e. for multipart messages including all MIME parts and boundaries, without transfer decoding. Like retrieve(), this marks the message as read (sets the \Seen flag).
Signature:
retrieveText( msgNum: number ): string
Parameters:
- msgNum:
numberThe number of the message whose text body to retrieve.
Return type: string
Example:
let text = myClient.retrieveText(1);
search()¶
Searches the currently selected (or examined) mailbox and returns the numbers of the matching messages. All given criteria must match; without criteria all messages are returned. since and before compare the date the server received the message (day precision).
Signature:
search( criteria?: infinity.imap4.searchCriteria ): Array<number>
Parameters:
- criteria:
infinity.imap4.searchCriteriaOptional, the search criteria.
Return type: Array<number>
Example:
// Unread messages of the last 30 days
let numbers = myClient.search({ since: Date.now() - 30 * 24 * 3600 * 1000, seen: false });
selectMailbox()¶
Selects a mailbox in the account for read-write access and returns its status as a infinity.imap4.mailbox object. Most message operations (such as retrieve(), delete() and count()) work on the currently selected mailbox.
Signature:
selectMailbox( name: string ): infinity.imap4.mailbox
Parameters:
- name:
stringThe name of the mailbox to select (e.g.
'INBOX').
Return type: infinity.imap4.mailbox
Example:
let inbox = myClient.selectMailbox('INBOX');
console.debug(inbox.totalMsgs + ' messages, ' + inbox.unseenMsgs + ' unseen');
size()¶
Returns the size of the specified message in bytes, or the total size of the currently selected mailbox if no message number is specified. Returns -1 if the size cannot be determined.
Signature:
size( msgNum?: number ): number
Parameters:
- msgNum:
number, optionalThe number of the message to examine. If unspecified, the total size of the selected mailbox is returned.
Return type: number
Example:
let messageSize = myClient.size(1);
let mailboxSize = myClient.size();
uid()¶
Returns the unique identifier (UID) of the specified message in the currently selected mailbox.
Signature:
uid( msgNum: number ): string
Parameters:
- msgNum:
numberThe number of the message.
Return type: string
Example:
let messageUid = myClient.uid(1);
uidSearch()¶
Like search(), but returns the unique identifiers (UIDs) of the matching messages. UIDs stay the same as long as the uidValidity of the mailbox does not change, so they can be used to remember which messages were processed already.
Signature:
uidSearch( criteria?: infinity.imap4.searchCriteria ): Array<string>
Parameters:
- criteria:
infinity.imap4.searchCriteriaOptional, the search criteria.
Return type: Array<string>
Example:
let allUids = myClient.uidSearch();
infinity.imap4.client¶
infinity.imap4.client.authMode¶
Values:
-
userPass:
0Authenticate using username and password.
-
sasl:
1Authenticate using SASL (Simple Authentication and Security Layer). The mechanisms CRAM-SHA1, CRAM-MD5, PLAIN and LOGIN are offered in this order; the first one the server supports is used (since 3.12; before, SASL login always failed).
-
xoauth2:
2Authenticate with an OAuth 2.0 access token (SASL mechanism XOAUTH2), as required by Microsoft 365 / Exchange Online / Outlook.com and Google (Gmail, Google Workspace). Set
usernameto the mailbox address andpasswordto the access token; getting and renewing the token (OAuth authorization code flow) is up to the script. Only XOAUTH2 is used, there is no fallback to other mechanisms. If the server rejects the token, the exception contains the server's answer (e.g.Invalid credentials), so the script can renew the token and connect again. Since 3.20.
Example:
infinity.loadModule('infinity.imap4');
let authMode = infinity.imap4.client.authMode.userPass;
infinity.imap4.client.encryptMode¶
Values:
-
none:
0Unencrypted connection.
-
sslTls:
1SSL/TLS encrypted connection.
Example:
infinity.loadModule('infinity.imap4');
let encryptMode = infinity.imap4.client.encryptMode.sslTls;
mailbox¶
An object describing the status of an IMAP4 mailbox, as returned by selectMailbox() and examineMailbox(). It has the following properties:
name:string- the name of the mailboxtotalMsgs:number- the total number of messages in the mailboxrecentMsgs:number- the number of messages with the\Recentflag setunseenMsgs:number- the number of messages that have not been read yet (requested withSTATUS; before 3.11 always0forselectMailbox()/examineMailbox())firstUnseenMsg:number- the message number of the first unseen messageuidNext:string- the UID that will be assigned to the next messageuidValidity:string- the UID validity value of the mailbox
messageFlags¶
The flags of a message, as returned by flags():
seen:boolean- the message has been readanswered:boolean- the message has been answeredflagged:boolean- the message is flagged for urgent or special attentiondeleted:boolean- the message is marked for removal by the next expungedraft:boolean- the message is a draftrecent:boolean- the message arrived recently in this mailbox
searchCriteria¶
The criteria of search() and uidSearch(); all given ones must match:
since:number- received on or after this time (milliseconds since 1970-01-01, day precision)before:number- received before this time (milliseconds, day precision)seen:boolean- read (true) or unread (false)deleted:boolean- marked as deleted (true) or not (false)from,to,subject:string- the field contains the texttext:string- header or body contain the text
mailboxArray¶
Extends: Array<string>
An array of IMAP4 mailbox (folder) names.