Documentation: Retrieving OTP Sent by Mail with JavaScript Library
This document provides guidance on retrieving a One-Time Password (OTP) sent via email using the otp-device-sync
JavaScript library. This method is particularly useful for automated test scenarios that require email-based OTPs for two-factor authentication (2FA).
Installation
First, install the otp-device-sync
library from NPM:
npm install otp-device-sync
Importing the Function
The library includes the getMailComponents
function, which can be used to retrieve the OTP and additional details from an email.
import { getMailComponents } from 'otp-device-sync';
Function Overview: getMailComponents
Purpose: Retrieve an OTP sent via email for a specified user and service.
Function Parameters
The getMailComponents
function requires the following parameters:
- user:
string
(required)
The email address of the user receiving the OTP. - service:
string
(required)
The identifier for the service sending the OTP (e.g., email domain or sender name). - options:
object
(required)verbose
:boolean
(optional) – Whentrue
, enables logging for debugging.timeout
:number
(optional) – The timeout in milliseconds. Defaults to 5 minutes.registeredKey
:string
(required) – The unique API key to authenticate and authorize the OTP retrieval.
Return Value
The getMailComponents
function returns a Promise<MailComponents>
object containing:
- code:
string
– The OTP code. - text:
string
– The plain text version of the email message. - html:
string
– The HTML version of the email message.
Example Usage
Here’s an example of how to retrieve an email OTP using the getMailComponents
function:
import { getMailComponents } from 'otp-device-sync';
(async () => {
try {
const mailComponents = await getMailComponents("user@example.com", "ServiceName", {
verbose: true,
timeout: 300000, // 5 minutes in milliseconds
registeredKey: "YOUR_REGISTERED_KEY"
});
console.log(`Retrieved Email OTP: ${mailComponents.code}`);
console.log(`Email Text: ${mailComponents.text}`);
console.log(`Email HTML: ${mailComponents.html}`);
} catch (error) {
console.error(`Error retrieving Email OTP: ${error.message}`);
}
})();
Key Points
- Time Sensitivity: Retrieve the OTP promptly, as it may expire.
- Authentication: Ensure
registeredKey
is stored securely, as it is required to authorize the request. - Error Handling: Use try/catch blocks to handle potential errors effectively.
Verbose Mode
Setting verbose: true
in the options enables logging for each step of the retrieval process, which is helpful for debugging.
Summary
The otp-device-sync
library simplifies email-based OTP retrieval, streamlining 2FA testing in automated environments. The getMailComponents
function allows easy integration of OTP retrieval into end-to-end tests, making it a valuable tool for ensuring 2FA flows work reliably across test scenarios.