otp-email-sender
v1.0.1
Published
A secure and easy-to-use 6-digit OTP generator and email sender using NodeMailer. Perfect for authentication flows in Node.js and Next.js applications.
Downloads
53
Maintainers
Readme
🔐 OTP Email Sender
A secure and easy-to-use 6-digit OTP generator and email sender using NodeMailer. Perfect for authentication flows in Node.js and Next.js applications.
✨ Features
- 🔒 Cryptographically secure OTP generation
- 📧 Multiple email templates (default, minimal, styled)
- ⚡ Easy integration with Express.js, Next.js, and other frameworks
- 🛡️ Built-in verification and expiry handling
- 📱 Customizable OTP length (4-8 digits)
- 🎨 Template customization with your branding
- 🧪 TypeScript support with full type definitions
- 🚀 Zero dependencies except NodeMailer
📦 Installation
npm install otp-email-sender🚀 Quick Start
const OTPEmailSender = require('otp-email-sender');
// Initialize with your email configuration
const otpSender = new OTPEmailSender({
service: 'gmail',
user: '[email protected]',
pass: 'your-app-password', // Use app-specific password
otpLength: 6,
expiryMinutes: 10
});
// Send OTP
const result = await otpSender.sendOTP({
to: '[email protected]',
subject: 'Your Login Code',
template: 'styled'
});
// Verify OTP
const verification = otpSender.verifyOTP('[email protected]', '123456');
console.log(verification.success); // true or false📖 API Reference
Constructor
new OTPEmailSender(config)config object properties:
service(string): Email service ('gmail', 'outlook', 'yahoo', etc.)user(string): Your email addresspass(string): Your email password or app-specific passwordfrom(string, optional): From email address (defaults touser)otpLength(number, optional): OTP length, 4-8 digits (default: 6)expiryMinutes(number, optional): OTP expiry time in minutes (default: 10)
Methods
sendOTP(options)
Sends an OTP via email.
Parameters:
to(string): Recipient email addresssubject(string, optional): Email subjecttemplate(string, optional): Email template ('default', 'minimal', 'styled')customData(object, optional): Custom data for email templates
Returns: Promise resolving to:
{
success: true,
otp: "123456",
messageId: "...",
to: "[email protected]",
expiresAt: "2025-01-27T..."
}verifyOTP(email, otp)
Verifies an OTP for a given email.
Returns:
{
success: true,
message: "OTP verified successfully"
}
// or
{
success: false,
error: "Invalid OTP"
}generateOTP(length?)
Generates a secure random OTP.
Returns: String OTP
cleanupExpired()
Removes expired OTPs from memory. Call periodically to prevent memory leaks.
🎨 Email Templates
Default Template
Professional template with clear formatting and your custom branding.
Minimal Template
Clean and simple design for basic use cases.
Styled Template
Modern gradient design with enhanced visual appeal.
Custom Data
Personalize templates with:
{
title: 'Welcome Back!',
companyName: 'Your Company',
footer: 'If you didn\'t request this, please ignore.'
}🔧 Framework Integration
Express.js
const express = require('express');
const OTPEmailSender = require('otp-email-sender');
const app = express();
const otpSender = new OTPEmailSender({
service: 'gmail',
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS
});
// Send OTP endpoint
app.post('/api/send-otp', async (req, res) => {
try {
const { email } = req.body;
const result = await otpSender.sendOTP({
to: email,
template: 'styled'
});
res.json({
success: true,
message: 'OTP sent successfully',
expiresAt: result.expiresAt
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
// Verify OTP endpoint
app.post('/api/verify-otp', (req, res) => {
try {
const { email, otp } = req.body;
const result = otpSender.verifyOTP(email, otp);
if (result.success) {
res.json({ success: true, message: 'OTP verified' });
} else {
res.status(400).json({ success: false, error: result.error });
}
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});Next.js (App Router)
// app/api/auth/send-otp/route.js
import OTPEmailSender from 'otp-email-sender';
const otpSender = new OTPEmailSender({
service: 'gmail',
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
});
export async function POST(request) {
try {
const { email } = await request.json();
const result = await otpSender.sendOTP({
to: email,
template: 'styled',
customData: {
title: 'Your Login Code',
companyName: 'My App'
}
});
return Response.json({
success: true,
message: 'OTP sent successfully',
expiresAt: result.expiresAt
});
} catch (error) {
return Response.json(
{ success: false, error: error.message },
{ status: 500 }
);
}
}Next.js (Pages Router)
// pages/api/auth/send-otp.js
import OTPEmailSender from 'otp-email-sender';
const otpSender = new OTPEmailSender({
service: 'gmail',
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
});
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const { email } = req.body;
const result = await otpSender.sendOTP({
to: email,
template: 'default'
});
res.json({
success: true,
message: 'OTP sent successfully',
expiresAt: result.expiresAt
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
}🔒 Security Best Practices
- Environment Variables: Store email credentials in environment variables
- App Passwords: Use app-specific passwords instead of regular passwords
- HTTPS Only: Always use HTTPS in production
- Rate Limiting: Implement rate limiting for OTP requests
- Don't Log OTPs: Never log OTP values in production
- Memory Management: Call
cleanupExpired()periodically
📧 Email Service Setup
Gmail
- Enable 2-factor authentication
- Generate an app-specific password
- Use the app password in your configuration
Outlook/Hotmail
- Enable 2-factor authentication
- Create an app password
- Use 'outlook' as the service
Other Providers
Most major email providers are supported. See NodeMailer documentation for the full list.
🧪 Testing
Run the included tests:
npm testRun examples:
npm run example🛠️ Environment Variables
Create a .env file:
EMAIL_SERVICE=gmail
[email protected]
EMAIL_PASS=your-app-password⚠️ Production Considerations
- Use a database or Redis instead of in-memory storage for OTPs
- Implement rate limiting to prevent abuse
- Set up proper error monitoring
- Use secure session management
- Implement proper user authentication
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
📞 Support
If you have any questions or need help, please:
- Open an issue on GitHub: https://github.com/IvanLimChoonKiat/otp-email-sender/issues
- Check the examples in the
/examplesfolder - Read the documentation above
Made with ❤️ for the Node.js community
