Blog

Guide to OTP messages: What are they and how to set them up

Amy Elliott Amy Elliott
· 24 min read · Tips and resources · October 28th, 2026
OTP messages have two big benefits: they boost the customer experience by improving the login process, and they make apps and websites more secure by preventing hackers from gaining account access.

In this guide, we’ll cover how OTP messages work, the types of OTPs you can use, best practices for setting them up, and how you can easily start sending them via email, SMS and WhatsApp with MailerSend. Let’s get to it!

What are OTP messages?

A one-time password (sometimes referred to as a one-time passcode) message is typically a text, email, or WhatsApp message containing an algorithm-generated single-use password used to authenticate a transaction or login session. 

These codes are sent to the user via a trusted contact method, expire after a short window, and can only be used once. This makes them an effective way to let people securely log in to your app or website. 

OTPs can be used 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 that involves the user logging in with static credentials and then using an OTP as an additional layer of authentication to verify the login.

What does an OTP message look like

An OTP message is typically short and functional: it delivers a code or link, says what the message is for, highlights when the code or link expires, and warns the recipient not to share it.

Here’s an example of an OTP from the 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:

An example of an SMS OTP from OpenTable.

Email OTP:

An example of an email OTP from OpenTable.

Types of OTPs

There are three types of OTPs: time-based one-time passwords (TOTPs), hash-based one-time passwords (HOTPs), and transmission-based one-time passwords.

Each type 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 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.

An example of a TOTP with an authentication app.

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 time step are input into a cryptographic hash function. The OTP must then be used within the assigned time step before it becomes invalid.

Graph showing how TOTP works.

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.

An example of a physical key that uses hash-based OTPs. Image source: Yubico.

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.

Graph showing how HOTP works.

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 text message, email, or a messaging service.

Here’s an example of a transmission-based OTP from the food delivery app, Deliveroo.

An example of a transmission-based OTP SMS from 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, WhatsApp or another instant messaging service like Viber.

Note:

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.

How do OTP messages work?

OTP messages work when a trigger causes the server to generate a password. This is then sent to the user via the chosen messaging service. 

Here is a step-by-step breakdown of the whole flow. 

  1. Trigger: The user does something that needs verification, such as logging in, signing up, resetting a password, or approving a payment

  2. Generation: The server creates a random code, usually 4 to 8 digits, using a cryptographically secure random number generator so it can't be predicted

  3. Storage: The server saves the code (ideally hashed, like a password) along with your account ID, an expiry time (often 5 to 10 minutes), and an attempt counter

  4. Transmission: The app calls a messaging provider's API, such as an SMS gateway, a transactional email service like MailerSend, or the WhatsApp Business API. The provider sends the message to your number or address

  5. Verification: The user enters the code. The server checks that it matches, hasn't expired, and hasn't already been used

  6. Invalidation: If it matches, the code is deleted or marked as used so it can't be used again. After too many wrong attempts, the code is invalidated and you have to request a new one

The process happens in seconds, meaning the user can quickly and securely log in to their chosen app.

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 methods.

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 sending directly to the user's cell phone number.

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. 

WhatsApp 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:

A flowchart example of a multi-channel OTP delivery flow.

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. 

An example of an OTP message from a bank with security message.

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.

An example of an e-commerce OTP SMS.

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.

An example of an OTP message from an app.

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.

An example of a healthcare related OTP message with expiration window.

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

In a replay attack, a cybercriminal intercepts data sent over a network, such as login credentials, and then reuses it to log in as the user. 

A stolen static password can be reused again and again, making them susceptible to this kind of attack. But with OTPs set up as part of a 2FA setup, the password alone isn't enough to get in: the hacker also needs a valid OTP. 

And because each OTP expires quickly and can only be used once, even if a hacker is able to intercept a code, there’s a chance that it will be invalid by the time they try to use it.

2. Improve users’ security practices

Many users are lax about password security: they reuse the same password across accounts or choose ones that are easy to guess. 

Using OTPs instead of passwords removes this risk, since there's no weak password for hackers to exploit. Instead, a different password is generated for every log-in.

When OTPs are used alongside passwords as part of multi-factor authentication, they offset the weakness of a bad password by adding a second layer of security: even if a hacker gets hold of the password, they still need access to the user's device to get a valid code.

3. Convenient for the end-user

OTPs aren’t just a good way to protect your users’ accounts; they are also convenient to use. 

When OTPs are used instead of a password, users no longer need to remember passwords or manage a long list of saved ones; they just enter their contact details into your login form and then enter the code. 

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. 

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: It’s possible for hackers to port phone numbers to different SIMs. If they can do this, they can receive the OTP code and log in as the user.

    • 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.

Email

  • 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.

WhatsApp

  • 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 to10 minutes 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 send one-time passwords (OTPs) by email, SMS and WhatsApp through our developer-friendly APIs. MailerSend handles delivery, and your app handles generating, storing and checking the code.

The whole flow takes three steps:

  1. Generate a random code, store it with an expiry time, and link it to the user.

  2. Send the code by email, SMS or WhatsApp with MailerSend.

  3. Validate the code when the user enters it, then delete it so it can't be reused.

The examples below use our Node.js SDK, with the raw JSON request body shown for each channel too. SDKs are also available for PHP, Python, Go, Ruby, Java and Laravel.

Prerequisites

For every channel, you'll need:

Then, depending on the channel:

Channel

What you need

Email

Your sending domain added and authenticated

SMS

A Starter plan or higher and a phone number to send from. You can test for free with a trial phone number, which can only send to verified recipients. Both the sender and the recipient must be U.S. or Canadian numbers.

WhatsApp

A MailerSend account on the Hobby plan or above, with the WhatsApp add-on and a connected Meta Business Account. You can test for free in the Sandbox before connecting a business account.

Step 1: Generate and store the OTP

Create a 6-digit code with a cryptographically secure random generator. Store a hash of the code rather than the code itself, along with an expiry time and an attempt counter.

import crypto from "crypto";

const OTP_TTL_MS = 10 * 60 * 1000; // 10 minutes

function generateOtp() {
  // Secure random integer from 0 to 999999, padded to 6 digits
  return crypto.randomInt(0, 1_000_000).toString().padStart(6, "0");
}

function hashOtp(otp) {
  return crypto.createHash("sha256").update(otp).digest("hex");
}

async function createOtp(userId) {
  const otp = generateOtp();

  // Replace with your own database or cache (e.g. Redis)
  await db.otps.upsert({
    userId,
    hash: hashOtp(otp),
    expiresAt: Date.now() + OTP_TTL_MS,
    attempts: 0,
  });

  return otp; // Plain code, used only to send the message
}

Using upsert means a new request replaces any older code for the same user, so only the latest code works.

Step 2: Send the OTP

Once you have the code, send it on the channel your user chose. Pass the plain code to MailerSend as a personalization variable, never the hash.

Send OTPs by email

The easiest way to send OTP emails is with a template. Create one in MailerSend that includes the {{otp}} variable, plus any others you want to use, like {{name}} and {{company}}. You'll find the template ID and sending instructions under the template's settings.

A good OTP email is short and tells the user three things: the code, when it expires, and what to do if they didn't request it. For example:

Subject: Your {{company}} verification code

Hi {{name}},

Here's your verification code: {{otp}}

It expires in 10 minutes. If you didn't try to log in, you can ignore this email, but we recommend changing your password.

Then send it with the SDK:

import { MailerSend, EmailParams, Sender, Recipient } from "mailersend";

const mailerSend = new MailerSend({ apiKey: process.env.MAILERSEND_API_KEY });

async function sendOtpEmail(user, otp) {
  const emailParams = new EmailParams()
    .setFrom(new Sender("security@yourdomain.com", "Awesome Company"))
    .setTo([new Recipient(user.email, user.name)])
    .setSubject("Your Awesome Company verification code")
    .setTemplateId("your-template-id")
    .setPersonalization([
      {
        email: user.email,
        data: { name: user.name, company: "Awesome Company", otp },
      },
    ]);

  await mailerSend.email.send(emailParams);
}

If you're calling the API directly, send a POST request to https://api.mailersend.com/v1/email with your API token in the Authorization: Bearer header and this body:

{
  "from": {
    "email": "security@yourdomain.com",
    "name": "Awesome Company"
  },
  "to": [
    {
      "email": "jane@example.com",
      "name": "Jane"
    }
  ],
  "subject": "Your {{company}} verification code",
  "template_id": "your-template-id",
  "personalization": [
    {
      "email": "jane@example.com",
      "data": {
        "name": "Jane",
        "company": "Awesome Company",
        "otp": "482915"
      }
    }
  ]
}

Send OTPs by SMS

SMS sending works the same way, using your MailerSend phone number as the sender. Keep the message short: the code, the expiry, and your company name so the user knows who it's from.

import { MailerSend, SMSParams } from "mailersend";

const mailerSend = new MailerSend({ apiKey: process.env.MAILERSEND_API_KEY });

async function sendOtpSms(user, otp) {
  const smsParams = new SMSParams()
    .setFrom("+18332647501") // Your MailerSend phone number
    .setTo([user.phone])
    .setText("{{otp}} is your {{company}} verification code. It expires in 10 minutes.")
    .setPersonalization([
      {
        phone_number: user.phone,
        data: { company: "Awesome Company", otp },
      },
    ]);

  await mailerSend.sms.send(smsParams);
}

To call the API directly, send a POST request to https://api.mailersend.com/v1/sms with this body:

{
  "from": "+18332647501",
  "to": ["+12345678900"],
  "text": "{{otp}} is your {{company}} verification code. It expires in 10 minutes.",
  "personalization": [
    {
      "phone_number": "+12345678900",
      "data": {
        "company": "Awesome Company",
        "otp": "482915"
      }
    }
  ]
}

Putting the code at the start of the message means users can see it in the notification preview without opening the SMS.

Send OTPs by WhatsApp

Every business-initiated WhatsApp message has to use a template approved by Meta. For OTPs, that's an Authentication template: a fixed message with one variable for the code and a button that lets users copy it in one tap.

To get set up:

  1. Connect your WhatsApp Business Account to MailerSend under WhatsApp then Phone numbers.

  2. Create an Authentication template and submit it to Meta. You can create a custom template in MailerSend and then request approval directly. Approval can take up to 48 hours.

  3. Create an API token with the whatsapp_full scope.

Bear in mind that Meta has strict conditions about which businesses can use Authentication templates. You'll need:

  • A verified business and a Meta Business Account

  • A dedicated phone number that isn't already used on WhatsApp or with another provider (you can also get a number from Meta)

Find out more in our WhatsApp messaging knowledge base.

WhatsApp personalization works differently from email and SMS. Instead of named variables, you pass values in order: the first value fills {{1}}, the second fills {{2}}, and so on. Authentication templates expect exactly one body value, the code, which MailerSend also copies into the copy-code button automatically, so you can leave buttons empty.

import { MailerSend, WhatsAppParams, WhatsAppPersonalization } from "mailersend";

const mailerSend = new MailerSend({ apiKey: process.env.MAILERSEND_API_KEY });

async function sendOtpWhatsApp(user, otp) {
  const whatsappParams = new WhatsAppParams()
    .setFrom("15550001234") // Your connected WhatsApp sender
    .setTo([user.phone])
    .setTemplateId("your-template-id")
    .setPersonalization([
      new WhatsAppPersonalization(user.phone).setBody([otp]),
    ]);

  await mailerSend.whatsapp.send(whatsappParams);
}

To call the API directly, send a POST request to https://api.mailersend.com/v1/whatsapp/send with this body:

{
  "from": "15550001234",
  "to": ["+12345678900"],
  "template_id": "your-template-id",
  "personalization": [
    {
      "to": "+12345678900",
      "data": {
        "body": ["482915"]
      }
    }
  ]
}

You can find your template ID under WhatsApp then Templates. Want to test before connecting a business account? Activate the Sandbox under WhatsApp then Sandbox to send test messages to your own phone number with our sandbox templates.

Step 3: Validate the OTP

Add a field to your login or sign-up page where users can enter their code. When they submit it, check it against the stored hash, make sure it hasn't expired, and limit how many times they can try.

const MAX_ATTEMPTS = 5;

async function verifyOtp(userId, submittedOtp) {
  const record = await db.otps.find({ userId });

  if (!record) return { ok: false, reason: "no_code" };

  if (Date.now() > record.expiresAt) {
    await db.otps.delete({ userId });
    return { ok: false, reason: "expired" };
  }

  if (record.attempts >= MAX_ATTEMPTS) {
    await db.otps.delete({ userId });
    return { ok: false, reason: "too_many_attempts" };
  }

  const submittedHash = Buffer.from(hashOtp(submittedOtp));
  const storedHash = Buffer.from(record.hash);

  // Constant-time comparison to prevent timing attacks
  if (!crypto.timingSafeEqual(submittedHash, storedHash)) {
    await db.otps.update({ userId }, { attempts: record.attempts + 1 });
    return { ok: false, reason: "invalid" };
  }

  // Success: delete the code so it can't be used again
  await db.otps.delete({ userId });
  return { ok: true };
}

If the code has expired or the user ran out of attempts, show a clear message and a button to request a new code.

OTP security best practices

The code above covers the basics. To keep your OTP flow secure in production, also:

  • Keep expiry short. 5–10 minutes is enough for users to find the code without leaving a long window for attackers.

  • Add a resend cooldown. Make users wait around 30–60 seconds before requesting a new code, so nobody can flood an inbox or phone.

  • Rate-limit requests. Cap how many codes a single user, email address, phone number or IP can request per hour. This also protects you from SMS pumping fraud, where bots trigger texts to premium numbers.

  • Never log the plain code. Keep it out of your application logs, analytics and error reports.

  • Don't reveal whether an account exists. Show the same "We've sent you a code" message whether or not the email or phone number is registered.

  • Offer a fallback channel. If the OTP doesn’t arrive on the first channel, let users request the code by another one.

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.

More OTP setup FAQs

What does OTP stand for?

OTP stands for one-time password, sometimes written as one-time passcode. It’s a temporary code valid for a single login or transaction. You may also see it called a one-time PIN, OTAC or dynamic password.

What is an OTP message?

An OTP message is an SMS, email or instant messaging service message containing a one-time password. It confirms the person signing in controls the phone number or inbox on file, stopping an attacker who only has the password.

How long does an OTP code last?

It depends on the channel. RFC 6238 is the official specification for TOTP, the codes authenticator apps like Google Authenticator generate. It sets the default lifetime of each code at 30 seconds. Meanwhile, email, SMS and WhatsApp codes usually last 5 to 10 minutes. 

What is the difference between TOTP and HOTP?

TOTP codes come from a shared secret plus the current time, so they expire on a fixed clock. HOTP codes use an event counter and stay valid until the next code is requested. TOTP is generally safer.

Are OTPs secure?

OTPs are safer than static passwords because a stolen code expires almost immediately. They are not immune: SIM swapping, phishing and man-in-the-middle attacks can intercept them. Using a short expiry window and rate limiting reduces the risk.

How do I send OTP messages to my users?

Generate a random code server-side, store it with an expiry, then send it through a messaging API. MailerSend delivers OTPs over email, SMS and WhatsApp from one API, so you can fall back when a channel fails.

Amy Elliott
I’m Amy, Content Writer at MailerSend. As a child, I dreamt about writing a book and practiced by tearing pages from an A4 notepad and binding them with sugar paper. The book is pending but in the meantime, I love taking a deep dive into technical topics and sharing insights on email metrics and deliverability.