infinity.smtp¶
Module: infinity.smtp
The infinity.smtp namespace contains classes for sending messages through SMTP email servers as a client as well as building your own SMTP server.
client¶
Properties:
- allowUnsafeLegacyRenegotiation
- authMode
- encryptMode
- host
- password
- port
- timeout
- useLegacyServerConnect
- username
- verifyServerCertificate
Methods:
You can use the infinity.smtp.client object to connect to an SMTP server and send messages through 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 SMTP server, followed by calls to the other methods. authenticate() switches to the encrypted connection (explicit TLS, STARTTLS) and logs in; since 3.11 the send methods call it themselves if it was not called before (before 3.11 it had to be called after connecting and before sending). Make sure to call the free() method when finished, to release the memory allocated by the client object.
Example:
infinity.loadModule('infinity.smtp');
let myClient = new infinity.smtp.client();
try {
myClient.host = 'smtp.gmail.com';
myClient.port = 465;
myClient.encryptMode = infinity.smtp.client.encryptMode.sslTls;
myClient.authMode = infinity.smtp.client.authMode.default;
myClient.username = 'youraccount@gmail.com';
myClient.password = 'yourpassword';
myClient.connect();
myClient.authenticate();
myClient.sendFile('mail.eml');
myClient.disconnect();
} finally {
myClient.free();
}
mail.eml example:
To: recipientName@domain.com
From: youraccount@gmail.com
Subject: The Subject
X-Sender: youraccount@gmail.com
Content-Type: text/plain; charset=US-ASCII;
format=flowed
Content-Transfer-Encoding: 7bit
Mailbody text
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 SMTP client establish a connection nonetheless. Default: false.
authMode¶
Type: infinity.smtp.client.authMode
Gets and sets the authorization mode for the SMTP client to use, according to infinity.smtp.client.authMode. Default: none.
encryptMode¶
Type: infinity.smtp.client.encryptMode
Gets and sets the encryption mode for the SMTP client to use according to infinity.smtp.client.encryptMode. Default: none.
With sslTls, the client uses implicit TLS if port is 465, and explicit TLS (STARTTLS, done by authenticate()) on any other port. The server must offer STARTTLS, otherwise authenticate() fails (since 3.11; before, the client went on unencrypted and sent the login data and the messages in plain text).
host¶
Type: string
Gets and sets the SMTP server address to connect to.
password¶
Type: string
Gets and sets the password for authorization.
port¶
Type: number
Gets and sets the communication port with the SMTP server. Default: 25.
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 SMTP 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 SMTP client object instance. Doesn't accept parameters.
Signature:
constructor()
Example:
infinity.loadModule('infinity.smtp');
let myClient = new infinity.smtp.client();
authenticate()¶
Carries out the authentication process with the SMTP server, according to authMode. If encryptMode is sslTls with explicit TLS (any port other than 465), the connection is switched to TLS (STARTTLS) first. The send methods call it themselves if it was not called after connect() (since 3.11; before, it had to be called before sending, also with authMode none).
Signature:
authenticate(): boolean
Return type: boolean
Returns true if the client is authenticated (always with authMode none). With authMode default, false is returned if no username is set or the server doesn't offer the LOGIN method. An error is thrown if the server rejects the credentials.
Example:
myClient.authenticate();
connect()¶
Connects to the SMTP server and sends the greeting (EHLO/HELO). The initial properties should be set by the time connect() is called.
Signature:
connect(): void
Example:
myClient.connect();
disconnect()¶
Ends the SMTP session by sending the QUIT command.
Signature:
disconnect(): void
Example:
myClient.disconnect();
free()¶
Frees the memory previously occupied by the SMTP client object instance. An open connection is closed first.
Signature:
free(): void
Example:
myClient.free();
sendFile()¶
Sends an email, reading the email data from the specified file. The file is parsed with infinity.mail and the message is rebuilt from the parsed data before sending, so header fields that infinity.mail does not support are not transferred. The sender of the envelope (MAIL FROM) is the From address, the recipients (RCPT TO) are all To, CC and BCC addresses; BCC addresses are not written to the message header.
Signature:
sendFile( fileName: string ): void
Parameters:
- fileName:
stringFilename, relative path (location relative to the folder with the used INFINITY.JS executable file) or absolute path to the file. The file needs to contain an email in RFC822 format. You can use
infinity.mailto create an RFC822 string.
Example:
myClient.sendFile('mail.eml');
sendStream()¶
Sends an email, reading the email data from a stream (from its beginning, regardless of the current position). Like with sendFile(), the message is parsed and rebuilt with infinity.mail before sending.
Signature:
sendStream( stream: infinity.stream ): void
Parameters:
- stream:
infinity.streamStream from which to read the email data. The data needs to be in RFC822 format. You can use
infinity.mailto create an RFC822 string.
Example:
myClient.sendStream(myStream);
sendMail()¶
Sends an email, reading the email data from an infinity.mail object. The sender of the envelope (MAIL FROM) is the from address, the recipients (RCPT TO) are all recipients, cc and bcc addresses; bcc addresses are not written to the message header.
Signature:
sendMail( mail: infinity.mail ): void
Parameters:
- mail:
infinity.mailMail object from which to read the RFC822 data.
Example:
myClient.sendMail(myMail);
verify()¶
Verifies an address or username (sending a VRFY command to the smtp server) and returns the first line of the server's reply. An error is thrown if the server doesn't confirm the address (many servers don't support VRFY), and without username (before 3.11: undefined was returned).
Signature:
verify( username: string ): string
Parameters:
- username:
stringUsername or encoded address (an address in angle brackets
<...>).
Return type: string
Example:
myClient.verify('username');
server¶
Properties:
Methods:
To run an SMTP server using infinity.smtp.server you need to set script filenames in the server's onConnect, onLogin, etc. properties. These script filenames have to be relative to the script that created the server (usually your main script; before 3.11 only files below the folder of the main script were found) and these scripts will be called when the SMTP server receives the corresponding SMTP command from a client.
Within these scripts, you can access the infinity.smtp.session object, which will be filled with the parameters of the client's SMTP command. You will also use this SMTP session object to pass back your reply to the client. You can find the specifics per command in the documentation of each on... property.
The script files are checked when start() is called; an error is thrown if one of them does not exist. Clients have to log in (SMTP AUTH) before they can send a message, so you need an onLogin handler. Senders, recipients and messages are refused unless the onMailFrom, onRcptTo and onReceive handlers accept them.
Example:
infinity.loadModule('infinity.smtp');
let myServer = new infinity.smtp.server(true, false, 587);
myServer.onLogin = 'smtp/login.js';
myServer.onMailFrom = 'smtp/mailfrom.js';
myServer.onRcptTo = 'smtp/rcptto.js';
myServer.onReceive = 'smtp/receive.js';
myServer.start();
Properties
onConnect¶
Type: string
Script filename (relative to the main script) that will handle SMTP connection requests. Within that script, you can access the infinity.smtp.session object, which will contain the following properties:
id: SMTP session idip: IP address of the connecting SMTP clientport: port of the SMTP client connectiondata: custom session data (seedata)disconnect: this is a function that you can call to disconnect the connection.
These properties will remain valid throughout the SMTP session, so you can access these in the other SMTP command handlers, as well. The only exception is the id property, which will become invalid in the onDisconnect handler.
onDisconnect¶
Type: string
Script filename (relative to the main script) that will handle SMTP disconnects. Within that script, you can access the infinity.smtp.session object, which will contain the same properties described in the onConnect handler (except for the id property no longer being valid), plus username and password of the session.
onLogin¶
Type: string
Script filename (relative to the main script) that will handle SMTP login requests. Within that script, you can access the infinity.smtp.session object, which will contain the same properties described in the onConnect handler, plus the following:
username: the username for authenticationpassword: the password for authenticationauthenticated:false, set this totrueif the credentials are valid
The username and password properties will remain valid throughout the rest of the SMTP session, in addition to the properties described in the onConnect command handler. You should validate these credentials and set the authenticated property accordingly. If authenticated is not true after the script ran (or no onLogin handler is set), the login is refused, and the client can't send messages.
onMailFrom¶
Type: string
Script filename (relative to the main script) that will handle SMTP mail-from requests. Within that script, you can access the infinity.smtp.session object, which will contain the same properties described in the onConnect handler, plus the following:
address: sender addressaccept:false, set this totrueto accept the sender address. If it staysfalse(or noonMailFromhandler is set), the sender is refused.
onRcptTo¶
Type: string
Script filename (relative to the main script) that will handle SMTP recipient-to requests. Within that script, you can access the infinity.smtp.session object, which will contain the same properties described in the onConnect handler, plus the following:
address: recipient addressaccept:false, set this totrueto accept the recipient address. If it staysfalse, the recipient is refused (relay denied); without anonRcptTohandler all recipients are refused.
onReceive¶
Type: string
Script filename (relative to the main script) that will handle SMTP receive requests. Within that script, you can access the infinity.smtp.session object, which will contain the same properties described in the onConnect handler, plus the following:
msg: RFC822 email message data.received:false, set this totrueto signal to the client that the message has been received successfully. If it staysfalse, the client gets an error reply.
In the onReceive handler, you will get the message to be sent in the infinity.smtp.session.msg property. This will contain an RFC822 string, containing the message headers and contents. You can use infinity.mail to parse the string into an object to handle the sender, recipient, subject, content and attachments of the message.
You need to set the infinity.smtp.session.received property to true after you have stored or forwarded the message. Without an onReceive handler, all messages are refused.
Methods
constructor()¶
Creates an SMTP server object.
Signature:
constructor( ssl?: boolean, verifyCertificate?: boolean, port?: number, maxConnections?: number, poolSize?: number, minProtocol?: infinity.smtp.server.protocol, maxProtocol?: infinity.smtp.server.protocol )
Parameters:
-
ssl:
boolean, optionaltrueto accept encrypted connections (using TLS/SSL),falseto only accept unencrypted connections (not recommended). Default:false. Withssl, the server initially uses the certificate filesinfinity.crt,infinity.keyandinfinity.root.crtfrom theresourcesfolder next to the folder of the INFINITY.JS executable (if they exist); usesetCertificate()to use your own certificate. -
verifyCertificate:
boolean, optionaltrueto request and verify a client certificate (against the root certificate); connections from clients without a valid certificate are refused. Only effective if a root certificate file exists. Default:false. -
port:
number, optionalThe port on which to listen for SMTP client connections. Default:
465ifsslistrue, otherwise25. Withssl, port465uses implicit SSL; on any other port the server accepts unencrypted connections and handles STARTTLS requests by the client to switch to an encrypted connection. -
maxConnections:
number, optionalMaximum number of simultaneous connections. Default:
0(unlimited). -
poolSize:
number, optionalSize of the thread pool. If greater than
0, the server keeps a pool of threads that are reused for new connections; otherwise a new thread is created for each connection. Default:0. -
minProtocol:
infinity.smtp.server.protocol, optionalMinimal encryption protocol accepted. You can use this to refuse client connections that are using old (possibly obsolete) encryption protocols. Default: SSL 3.
-
maxProtocol:
infinity.smtp.server.protocol, optionalMaximum encryption protocol accepted. Default:
tls1_3.
Example:
infinity.loadModule('infinity.smtp');
let myServer = new infinity.smtp.server();
let mySslServer = new infinity.smtp.server(true, false, 465, 0, 0, infinity.smtp.server.protocol.tls1_2);
setCertificate()¶
Sets the SSL certificate for the current server instance using the corresponding files provided in the function parameters. Throws an error if the server was created without ssl. Files that do not exist are ignored.
Signature:
setCertificate( certFile: string, keyFile: string, rootCertFile?: string, verify?: boolean ): void
Parameters:
-
certFile:
stringThe path to the certificate file to be used.
-
keyFile:
stringThe path to the key file to be used.
-
rootCertFile:
string, optionalThe path to the root certificate file to be used.
-
verify:
boolean, optionaltrueto request and verify client certificates against the root certificate (only effective ifrootCertFileis given). Default:false.
Example:
myServer.setCertificate('certFile.crt', 'keyFile.key', 'rootCertFile.crt', true);
start()¶
Starts the SMTP server. The server will run as a separate thread, listening to incoming SMTP client connections and running the scripts specified in the on... command handlers.
Signature:
start(): void
Example:
myServer.start();
stop()¶
Stops the SMTP server. The server will close its port and stop listening for SMTP connections.
Signature:
stop(): void
Example:
myServer.stop();
infinity.smtp.client¶
infinity.smtp.client.authMode¶
Values:
-
none:
0No authentication (allow sending messages without authentication).
-
default:
1Authenticate using the default username and password method.
-
sasl:
2Authenticate 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:
3Authenticate 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. As with the other modes, the SMTP client logs in when the first mail is sent or whenauthenticate()is called, not inconnect(). Since 3.20.
Example:
infinity.loadModule('infinity.smtp');
let authMode = infinity.smtp.client.authMode.default;
infinity.smtp.client.encryptMode¶
Values:
-
none:
0Unencrypted connection.
-
sslTls:
1SSL/TLS encrypted connection.
Example:
infinity.loadModule('infinity.smtp');
let encryptMode = infinity.smtp.client.encryptMode.sslTls;
infinity.smtp.server¶
infinity.smtp.server.protocol¶
Values:
-
tls1:
2TLS 1.0 encrypted connection.
-
tls1_1:
3TLS 1.1 encrypted connection.
-
tls1_2:
4TLS 1.2 encrypted connection.
-
tls1_3:
5TLS 1.3 encrypted connection.
Example:
infinity.loadModule('infinity.smtp');
let protocol = infinity.smtp.server.protocol.tls1_2;
infinity.smtp.session¶
The infinity.smtp.session object will be available in the command handler scripts run by the infinity.smtp.server. The properties will be filled depending on the command handler and some of the properties are used to provide results of the handler to be returned back to the client.
accept¶
Type: boolean
This is a property that you need to set in the onMailFrom and onRcptTo command handlers to either accept or refuse the given address.
authenticated¶
Type: boolean
Only available in the onLogin command handler. You need to set this property to true or false depending on whether the provided credentials (username and password) are valid.
received¶
Type: boolean
Set this property to true or false in the onReceive command handler to notify the client of success or failure.
address¶
Type: string
This property will contain the sender or recipient email address in the onMailFrom and onRcptTo command handlers.
data¶
Type: any
Custom data that you can keep for the session. The value is stored as JSON, so it must be JSON-serializable. Values assigned in the onLogin, onMailFrom, onRcptTo and onReceive handlers are kept and are available in all later handlers of the same session; changes made in onConnect and onDisconnect are discarded. Initially undefined.
id¶
Type: number
The SMTP session id. This will remain constant throughout a single SMTP session and will turn invalid on disconnect.
ip¶
Type: string
The IP address from which the SMTP client connected.
msg¶
Type: string
In the onReceive command handler, this will contain the RFC822 message data to be sent. You can use infinity.mail to parse this RFC822 string and access the email's addresses, subject, contents and attachments.
password¶
Type: string
The password used to authenticate the SMTP session.
port¶
Type: number
The port used by the SMTP connection with the client.
username¶
Type: string
The username used to authenticate the SMTP session.
disconnect()¶
Disconnects the current SMTP connection.
Signature:
disconnect(): void