Improve security with OTPs: Guide to one-time passwords
- What are OTP messages?
- Types of OTPs
- Time-based one-time passwords (TOTPs)
- Hash-based one-time passwords (HOTPs)
- Transmission-based OTP
- Transmission-based OTPs: Choosing the right channel
- Real-world OTP use cases
- How your business can benefit from OTPs
- The risks of using OTPs
- OTP best practices
- How to send OTPs with MailerSend
- Set up OTP emails
- Set up OTP SMS
- Conclusion
They are a simple yet highly effective way to boost security, providing users with a unique password every time they log in.
In this guide, we’ll cover how OTPs work, the types of OTPs, best practices, and how you can easily set up and start sending them with MailerSend. Let’s get to it!
What are OTP messages?
A one-time password (sometimes referred to as a one-time passcode) is an algorithm-generated password used to authenticate a single transaction or login session.
OTPs can be used for the entire authentication process, for example, using an OTP to log in along with the user’s username, email address or phone number instead of a static, user-generated password. Or, they can be a part of a multi-layer authentication process, such as two-factor authentication (2FA) or multi-factor authentication (MFA). This involves the user logging in with static credentials and then using an OTP as an additional layer of authentication to verify the login.
Here’s an example of a OTP from restaurant reservation app, OpenTable. The user can enter either their cell phone number or email address and receive a one-time password to log in, rather than use the same password every time.
SMS OTP:
Email OTP:
OTPs offer additional security because:
a) They provide a unique password every single time the user completes a transaction or logs in; the password cannot be discovered and used again.
b) OTPs are stronger and more secure passwords that are made up of random characters compared to user-generated passwords, which are often weaker and more predictable.
Types of OTPs
There are three types of OTPs, each of which uses a different method to generate the password. The OTPs can be generated by a security token in the form of a device (hard token) or mobile phone app (soft token), or be delivered via SMS, instant message, or email.
Time-based one-time passwords (TOTPs)
TOTPs generate new passwords based on the current time, which are then usually delivered via an authenticator app (like Google Authenticator, Microsoft Authenticator or Authy) or via a hardware device.
An example would be the TOTPs used for 2-factor authentication for apps like Facebook or Slack.
They use two pieces of information to generate the OTP. The first is a static secret key or seed, which is known by the user’s token and the authentication server that validates the OTP. The second is the moving factor—in the case of TOTPs, a time-based counter. To calculate the time counter, a Unix timestamp is used along with the pre-set time limit (or timestep) of an OTP (typically 30 or 60 seconds).
To generate the OTP, the secret key and timestep are input into a cryptographic hash function. The OTP must then be used within the assigned timestep before it becomes invalid.
Hash-based one-time passwords (HOTPs)
These are also known as HMAC-based one-time passwords, as they use the hash-based message authentication code (HMAC) open-source standard.
A popular example is the Yubico YubiKey, a physical key that individuals can use via USB-C or by tapping against an NFC-enabled device for secure access to accounts.
Like TOTPs, HOTPs use a secret key or seed as well as a moving factor. The moving factor differs here, though, as it is based on an event-activated counter rather than time-based. The counter is stored in the token and on the server. The counter on the token counts the number of OTPs that are generated when the button on the token is pressed. The counter on the server counts the number of OTPs once each one is validated. This means that HOTPs are not time-limited.
To generate the hash-based OTP, the secret key and counter are inserted into a one-way cryptographic hash function that generates the OTP. Unlike TOTPs, it will remain valid until the user requests another OTP that is then validated.
Transmission-based OTP
This type of OTP implementation is the most common and one of the easiest ways to set up OTP. It involves generating unique, temporary passwords that are then sent to the user via push notification, text message or email.
Here’s an example from the food delivery app, Deliveroo.
Transmission-based OTP is easier to implement for developers as there is no need for two separate devices to create and validate the passwords. Password generation and authentication are done by the same server. The most common way to deliver passwords is by SMS or instant message via platforms like WhatsApp or Viber.
Hard vs. soft tokens
Hard tokens are physical devices that generate OTPs, such as USB drives, fobs, smart cards and bluetooth devices. An example of a popular OTP hardware provider is Yubico. Soft tokens refer to software that generates OTPs, such as authentication apps like Google Authenticator.
Transmission-based OTPs: Choosing the right channel
Transmission-based OTPs can be delivered through various channels, so which should you use? Email, SMS, and messaging apps like WhatsApp each have their own strengths, and the best solution likely uses a combination of the three.
Email OTPs
Email is one of the most widely used transactional messaging channels due to its broad reach, familiar format, ability to deliver more detailed, rich content, and cost-effectiveness.
It’s a solid solution for customers who prefer to receive OTPs via email, although it can result in slightly slower delivery times than SMS or instant messaging. Plus, if users are trying to log in from mobile, it’s less convenient than a mobile-first flow.
SMS OTPs
SMS is the most popular channel for the delivery of OTP and MFA messages, thanks to high deliverability rates and near instant delivery.
Since SMS is mobile native, it improves user flows with device features like cross-application auto-detection of OTPs. The caveat is that SMS relies on mobile carriers, and as a result, it costs more than email or instant messaging.
WhatsApp OTPs
Instant messaging apps like WhatsApp are quickly becoming popular channels for delivering transactional messages. And it makes sense: in 2025, WhatsApp reached 3 billion monthly users worldwide, with higher engagement than SMS or email in markets across Latin America, Asia, and Europe.
It allows for richer messaging experiences than SMS, with extremely high deliverability and open rates for a fraction of the cost. Plus, it offers end-to-end encryption, making it more secure. The main issue with WhatsApp transactional messaging is that, unlike SMS or email, the user must have the app installed, and without a third-party technology partner, direct integration with Meta and WhatsApp can be time-consuming and complex.
The best approach: A multi-channel OTP delivery flow
For maximum delivery success and a better user experience, give your customers options. A multi-channel OTP login flow could look like this:
By using email, SMS and WhatsApp, you can have multiple fallback methods in place, ensuring that those time-sensitive OTP messages get delivered without hindering the customer journey. And a smoother customer journey will also lead to fewer customer support interactions initiated by frustrated users who haven’t received an OTP message.
Real-world OTP use cases
Any organization can make its user accounts more secure with OTPs. If you have a system that requires customers or employees to log in, you can use OTPs. Here are a few example use cases.
Banking
Security is of the utmost importance in banking and financial services—there’s a lot at stake in the event that an account is compromised. Using OTPs is an excellent way to ensure customers’ account credentials cannot be accessed. In addition to logging in to accounts, OTPs can be used to verify large transactions, loan and credit card applications, account closures, and more.
E-commerce
For e-commerce stores, one-time passwords don’t just make accounts more secure; they also enhance the user experience. Users don’t need to remember or store endless passwords for different e-commerce websites—they can simply enter their email address or phone number and receive a unique, secure password.
SaaS
Software applications can contain huge amounts of sensitive data. Data that—if it gets into the wrong hands—can cause significant ramifications for organizations and their users. OTPs offer a simple solution that can improve SaaS security, removing the potential for human error and preventing brute-force attacks on user accounts.
Healthcare
Similarly, healthcare providers are guardians of a lot of sensitive information in the form of patient records. Implementing OTPs is one way to protect patients’ data and avoid HIPAA violations.
Digital agencies
As a digital agency, you can implement OTPs for your clients to help them improve security for their customers. But you can also use OTPs for any custom dashboards you create for them, to ensure a lower chance that their sensitive data becomes exposed.
How your business can benefit from OTPs
You’ve probably noticed the widespread use of OTPs from your own online experience. That’s because OTPs are a simple but reliable way to increase security. Let’s take a look at some of the benefits.
1. Prevent replay attacks
A replay attack involves a cybercriminal eavesdropping on a secure network, intercepting a data transmission and then delaying or repeating it. By using this method, hackers can intercept users’ passwords and then use them. OTPs can prevent this from happening as, by the time the cybercriminal attempts to use the password, it is no longer valid. Either because the time limit for the OTP has expired or it has already been used by the end-user and is therefore no longer valid for use.
2. Improve users’ security practices
Since many users are lax about the strength and security of their passwords, implementing OTPs as an alternative removes the potential for hackers to exploit them. Plus, using OTPs as part of a multi-factor authentication process helps to override the weakness of bad passwords by adding another layer of security that hackers can’t usually intercept.
3. Convenient for the end-user
OTPs are an easy and reliable way to protect your users' data and accounts from attack. Additionally, using OTPs makes it easier to manage account access—there’s no need to use bad (albeit memorable) passwords, try to remember stronger passwords, or keep them saved anywhere. Even better, OTPs are completely free for the end-user.
4. Quick, automated sending
Delivering new, randomly generated OTPs is super quick and painless—there’s no need for users to sit around waiting to log in or complete their purchase. Generating new OTPs via device or app is instant, and with the correct implementation and infrastructure, delivering OTPs via email or SMS is just as fast and seamless.
5. Compliance with privacy laws
Organizations handling the personal data of customers, users, and employees are required to take adequate measures to ensure an appropriate level of security. Implementing OTPs adds an additional layer of protection that can help them to comply with the relevant privacy laws, such as the GDPR.
Check out our guide on SMS compliance to learn more.
6. Keep IT admins happy
Password management requires a lot of time and effort to implement and maintain good practices. With OTPs, admins needn’t worry about security for password storage, policies, password rules and timelines, and so on. They can dedicate their time elsewhere while OTP automates everything.
The risks of using OTPs
One-time passwords are significantly more secure than static passwords, but, as with anything online, they’re not immune to attacks. This doesn’t mean you should avoid using them. Rather, it’s important to be aware of the vulnerabilities and take measures to avoid exposure.
SMS
SIM swapping: Mobile service providers are very easily able to port phone numbers to different sims. Attackers exploit this ability by contacting the phone number owner and using social engineering to gain information about them. They will then contact the user’s mobile service provider and use the information they gained to try and convince the provider that they have lost their phone and need their number to be ported to a different device. These types of attacks rely on users falling victim to the scam.
How to prevent SIM swapping: The vulnerabilities surrounding SIM swapping lie with the mobile carrier and the user. As a sender of OTPs, there isn’t much you can do besides educate your users on maintaining a safe digital footprint and the risks of SIM swapping, and encourage them to set a PIN code or passphrase with their carrier to prevent unauthorized action on their account.
SS7 flaw: SS7 (Signaling System No.7) is an outdated, although still in use, protocol that’s been around since the 70’s. It’s the leading protocol for connecting network communication worldwide, and it’s even used by intelligence agencies for surveillance purposes. Attackers use these same surveillance methods to hack the network and eavesdrop on people’s mobile phones. In fact, they can fool the network into believing that the hacker device is the device belonging to the subscriber, allowing them to intercept phone calls and text messages without the real owner knowing.
How to prevent SS7 attacks: For most businesses, the practical risk is low as this type of attack requires significant technical expertise, and is usually associated with large-scale criminal organizations or nation-state actors. But it’s smart to be aware of the potential risk.
Push-bombing attacks: This type of attack targets users using multi-factor authentication. Attackers will obtain the user’s account credentials and then attempt to log in many times, bombarding the user with authentication requests. The goal is to overwhelm the user so that they eventually confirm their identity and give the attacker unauthorized access.
How to prevent push-bombing attacks: Rate-limit failed authentication attempts to prevent the attacker from flooding the system and user with requests. It’s also best to use verification code authentication, so that the user has to enter the code rather than click a link, removing the chance of panic-clicking by mistake.
Phishing and spoofing attacks: Email OTPs are increasingly targeted through impersonation attacks, where users are tricked into handing over their codes to an attacker by pretending to be someone else or posing as a business. Coinbase is one example where multiple impersonation phishing attacks have been identified. Typically, attackers pose as customer support agents and tell users that their accounts have been compromised, then manipulate them into handing over their 2FA codes or sending them to fake Coinbase pages to enter their login details.
How to prevent phishing and impersonation attacks: Ensure that you are using proper email authentication with SPF and DKIM, and enforce a strict DMARC policy of p=reject. This will ensure that anyone trying to spoof your domain will have their emails rejected. You should also make it clear that you will never ask users for their OTP or 2FA codes, and include this in your emails.
Man-in-the-middle attacks: MITM attacks are more effective when email encryption and authentication are not used. They involve the attacker intercepting the data exchange between two parties and stealing information, such as account credentials.
How to prevent man-in-the-middle attacks: Ensure all OTP delivery runs over HTTPS and implement proper authentication with SPF, DKIM and DMARC for your sending domain.
SIM swapping: While SIM swapping doesn’t directly provide access to WhatsApp, since WhatsApp accounts are tied to phone numbers, attackers can use re-routed SMS verification codes to access them on their own device.
Phishing and impersonation: Just as with email, attackers can impersonate businesses in WhatsApp and directly request users’ OTPs or direct them to fake webpages to enter their login details. To prevent this kind of attack on WhatsApp, let users know that you’ll never ask for their passwords or OTPs. You can also verify your business profile, so that it displays a checkmark badge to recipients, identifying you as a real sender.
OTP best practices
Sending one-time passwords is pretty straightforward; you can do it with a simple code snippet. Where it gets trickier is sending them securely and reliably at scale. Here are the best practices for a solid OTP strategy.
1. Use expiry windows
If an OTP never expires, it may as well be a static password. Setting an expiry window will limit the potential for damage if it happens to be intercepted or leaked.
The shorter the expiry window, the better. If a user is attempting to log in, the chances are they’ll use it immediately anyway. So an expiry window of 5-10 minutes for SMS and instant messages, and 30 minutes to 1 hour for emails, should give them plenty of time to enter the code. Just be sure to inform the user that the code will expire in the message, e.g., “This code will expire in 5 minutes.”
2. Implement rate limiting for OTP requests
Remember push-bombing attacks? Where attackers try to log in many times in quick succession to overwhelm the user? The best way to prevent this is to implement rate limiting on the endpoint that triggers OTP delivery.
Setting a limit of 3 to 5 requests per 10-minute window, with exponential backoff after the first window, is a good starting point.
3. Limit failed entry attempts
To prevent attackers from guessing OTPs through brute force, it’s best to allow only a limited number of OTP entry attempts. If a code is entered 5 times incorrectly, the OTP should become invalid, and the user would need to request a new one.
For an even stronger approach, you can combine this with progressive delays in OTP requests, requiring the user to wait longer each time code entry fails.
4. Ensure seeds and secrets are not exposed
The shared secret or seed used to generate OTPs must be stored securely on your server. If exposed, it can be used to generate working OTPs for users, allowing attackers to gain access.
Treat all stored secrets as you would your API keys. They should be encrypted, never logged, and never returned in API responses.
5. Use proper email authentication
When a user triggers an OTP, they expect to receive it in their inbox immediately so they can log in. Email authentication will help to ensure your important transactional emails land in the inbox and not in the junk folder.
Plus, not only will SPF, DKIM and DMARC improve deliverability and inbox placement, but they will also help prevent attackers from spoofing your domain and carrying out phishing scams on your users.
6. Keep your messages clear and informative
Your OTP messages are also an opportunity to improve the user experience and overall security of your app. It should:
Be clear about what the code is for and who it is from
Define the expiry window of the code
Confirm that the user should never share the code, and no one from your team will ever ask for it
How to send OTPs with MailerSend
With MailerSend, you can easily send OTPs via SMS and email thanks to our developer-friendly APIs. Let’s take a look at how to set up both.
Prerequisites:
A MailerSend account. For sending emails, you can start for free with up to 500 emails/month. For sending SMSes, you’ll need a Starter plan
Your domain added to MailerSend and authenticated (for sending emails)
A verified phone number (for sending SMSes). You can use a trial phone number to get started, or purchase one via our add-ons
An API key with the appropriate permissions
The relevant MailerSend package installed
In order to have the one-time password, you'll need to create a function to generate a random number and add a validity timeframe to the function. You'll also need to create the function to validate the OTP when the user enters it.
Once you’re done, you can choose between sending the OTP via email or text:
Set up OTP emails
Send an email using one of your templates—remember the sending instructions are available under the template settings!
Be sure to include a variable containing your random number like {{otp}}. You can then use the following code to send an HTML email:
{
"from":{
"email":"hello@{{sendingdomain}}",
"name":"Awesome Company"
},
"to":[
{
"email":"jane@mailersend.com"
}
],
"subject":"Your {{company}} verification code",
"html":"<b>Hi {{name}}!</b>
<br>
<br>To help us make sure it's really you, here's the verification code you'll need to log in:
<br>
<b>{{otp}}</b>.
<br>
<br>
If this wasn't you logging in, and you use a password to log in, please reset your password. To further secure your account, please set up two-step authentication.
<br>
This code will expire in <b>1 hour</b>. Once the code expires, you will need to request a new verification code by going through the login procedure again",
"personalization":[
{
"email":"agathe+1@mailersend.com",
"data":{
"company":"MailerSend",
"name":"Jane",
"otp":"1234567890"
}
}
]
}
Set up OTP SMS
You can follow the same method to send an SMS, using the following code:
{
"from":"+18332947701",
"to":[
"+18332403627"
],
"text":"Hey {{name}}! Your {{company}} verification code is {{otp}}. ",
"personalization":[
{
"phone_number":"+18332403627",
"data":{
"name":"Jane",
"otp":"1234567890"
}
}
]
}Make sure you have a field on your login page that appears when the user enters their email address so that they can enter the one-time password.
Developer resources for sending emails and SMS messages
Guides for sending emails:
Guides for sending SMS:
Official API documentation:
OTP for a secure, reliable user experience
OTPs are more than just another type of transactional message you can send your recipients. It’s a way to improve security for your business and users, and provide a better, more professional customer experience. Implementing some form of OTP, either for login, transaction verification or MFA, is a must for businesses that prioritize security.
Will you be using MailerSend to send OTP emails or text messages to your users? Tell us about your use case in the comments!
Start using OTPs now!
Sign up to MailerSend’s transactional messaging service to start sending OTP SMS and emails. Get 500 emails free or upgrade to get SMS, more emails and advanced features.