mail system in node js , express js
mail system in node js , express js
Mailtrap offers a free plan called the "Free Plan", which is designed for testing and
development purposes. It includes the following features:
500 test emails per month (this means you can send up to 500 emails for testing
purposes)
1 team member (you can only have one user in the free plan)
Limited email logs (a limited retention time for email logs, usually for a short period)
This free plan is useful for individual developers or small teams who want to test email
functionality during development. However, if you need more features like more inboxes,
higher email volume, or collaboration with a team, you would need to upgrade to a paid
plan.
You can sign up for the free plan on the Mailtrap website.
bash
mkdir my-app
cd my-app
npm init -y
1/11
2. Install required dependencies:
bash
jsonwebtoken: For creating and verifying tokens (for password reset and email
verification).
ini
EMAIL_HOST=smtp.your-email-provider.com
EMAIL_PORT=587
[email protected]
EMAIL_PASS=your-email-password
JWT_SECRET=your-jwt-secret-key
FRONTEND_URL=http://localhost:3000 # Update with your actual frontend URL
Note: You can use email services like SendGrid, Mailgun, Amazon SES, or even a personal
SMTP server. These services offer reliable email sending without the limits of Mailtrap.
js
// emailService.js
const nodemailer = require('nodemailer');
require('dotenv').config();
2/11
// Configure the SMTP transporter
const transporter = nodemailer.createTransport({
host: process.env.EMAIL_HOST,
port: process.env.EMAIL_PORT,
secure: false, // Use TLS
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
return transporter.sendMail(mailOptions);
};
module.exports = { sendEmail };
js
// authController.js
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { sendEmail } = require('./emailService');
const User = require('./models/User'); // Replace with your User model
3/11
// Forgot Password: Generate reset token and send via email
const forgotPassword = async (req, res) => {
const { email } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ message: 'User not found' });
}
try {
await sendEmail(
email,
'Password Reset Request',
`Click here to reset your password: ${resetUrl}`,
`<a href="${resetUrl}">Click here to reset your password</a>`
);
if (!user) {
return res.status(400).json({ message: 'Invalid user' });
}
4/11
res.status(200).json({ message: 'Password updated successfully' });
} catch (error) {
res.status(400).json({ message: 'Invalid or expired token' });
}
};
js
// authController.js (continued)
try {
await sendEmail(
user.email,
'Email Verification',
`Click here to verify your email: ${verificationUrl}`,
`<a href="${verificationUrl}">Click here to verify your email</a>`
);
} catch (error) {
throw new Error('Error sending email verification link');
}
};
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded.userId);
if (!user) {
5/11
return res.status(400).json({ message: 'Invalid user' });
}
6. Set Up Routes
In your routes file, you can set up routes for these functionalities.
js
// authRoutes.js
const express = require('express');
const router = express.Router();
const { forgotPassword, resetPassword, verifyEmail } = require('./authController');
module.exports = router;
js
// server.js
const express = require('express');
const dotenv = require('dotenv');
6/11
const cors = require('cors');
const authRoutes = require('./authRoutes');
dotenv.config();
app.use('/api/auth', authRoutes);
Make sure the email provider you're using is configured correctly and can send emails.
Use Postman or any API testing tool to test the forgot password and email verification
routes.
Important Notes:
1. Email Provider: Use a service like SendGrid, Mailgun, or Amazon SES for production, as
free providers like Gmail might have limitations on sending mass emails or using SMTP
for a production app.
2. Security: Ensure you are hashing passwords securely and storing sensitive information
like API keys in environment variables.
Conclusion
With this setup, you can handle forgot password and email verification flows in your
Node.js + Express.js app without relying on limited services like Mailtrap. You'll have full
control over email sending and can scale based on your needs.
7/11
Choosing between SendGrid, Mailgun, and Amazon SES depends on your specific use case,
volume, and budget. Each of these services offers different strengths, so let's break down the
key factors to help you decide:
1. SendGrid
Features: It offers features like email tracking, analytics, and templates, which can be
helpful if you need more than just basic email sending.
Scalability: It's great for both small and large-scale applications. You can start with the
free plan (up to 100 emails/day) and scale as your email volume grows.
Pricing: Offers a free tier (up to 100 emails/day), and pricing increases as your sending
volume goes up. Its pricing model is transparent, which makes it easy to understand
costs.
You want advanced features like email analytics, template management, and email
tracking.
You're planning to scale quickly and want a well-documented service that handles this.
2. Mailgun
Best For: Developers and flexibility, especially if you need advanced email features.
Features: It includes advanced features like email validation, in-depth analytics, and
automated email flows.
Scalability: It handles large-scale email sending very well and offers detailed analytics.
Pricing: Mailgun offers a free tier with 5,000 emails for the first three months, then it
charges on a pay-as-you-go basis. It’s slightly more expensive than SendGrid but offers
8/11
higher flexibility for larger needs.
You're looking for more flexibility and control over your email flows.
You’re a developer or have a team with technical expertise that requires advanced
configurations.
Pricing: Amazon SES is the most cost-effective option, especially for high-volume email
sending. It charges based on the number of emails sent (roughly $0.10 per 1,000
emails). This makes it ideal if you're sending a large volume of emails and need to keep
costs low.
Features: SES offers fewer features compared to SendGrid or Mailgun (e.g., lacks
advanced email templates or in-depth analytics out of the box). However, you can
integrate it with other AWS services for more advanced functionality (e.g., AWS Lambda
for custom workflows).
Scalability: It's highly scalable and supports sending large volumes of email, making it a
solid choice for applications that expect to scale significantly.
You need the most cost-effective option for high-volume email sending.
You're already within the AWS ecosystem and prefer a solution that integrates with your
existing infrastructure.
You don't need advanced features like email templates or detailed analytics.
Comparison Summary
9/11
Feature SendGrid Mailgun Amazon SES
Pricing Free tier (100 emails/day), Free tier (5,000 emails for Extremely cost-effective,
pay-as-you-go 3 months), pay-as-you-go pay-as-you-go
Scalability Good, with paid plans for Good, designed for high Excellent for high
high volumes volume volumes
Features Advanced analytics, email Powerful features like Basic email sending,
templates, tracking email validation, routing limited analytics
Integration Simple integration, third- Good API, developer tools Best if already using AWS
party support services
For Ease of Use with Advanced Features: SendGrid is an excellent option if you want a
user-friendly interface with robust features like email tracking, templates, and analytics.
It's scalable and provides everything you need to grow without significant technical
overhead.
For Developers Needing Advanced Flexibility: Mailgun would be the best choice if you
need advanced features like email validation, routing, or even building custom email
workflows. It’s great for developers and teams that need fine-grained control over email
sending, but it may come at a slightly higher price than SendGrid.
Conclusion:
If you're just getting started and need simplicity, SendGrid is often the easiest option with
good features. If you want to maximize cost-effectiveness and plan on sending a large
volume of emails, Amazon SES will be your best bet. Mailgun fits well if you need advanced
developer features and have the technical expertise to handle more complex setups.
10/11
so i can use mailtrap free for ever ?
Mailtrap's free plan is available indefinitely, but it does come with some limitations. Here's a
breakdown of what you get with the Mailtrap free plan:
500 test emails per month: You can send up to 500 emails per month for testing.
1 team member: The free plan allows only one user to access the inbox.
Limited email logs: The email logs are stored for a limited time (usually up to 7 days).
Basic email preview: You can preview and inspect the contents of the emails sent to the
inbox.
2. Limited functionality: Some features, such as email API access, integration with more
inboxes, and advanced reporting, are only available on higher-paid plans.
3. Only one user: You can’t add multiple team members in the free plan.
Conclusion:
You can use Mailtrap for free indefinitely as long as you stay within the limits of the free
plan (500 emails per month, 1 inbox, etc.). If your email testing needs exceed those limits,
you would need to explore one of Mailtrap’s paid options.
If you're building a system in development and just need to test email functionality,
Mailtrap's free plan is a great option. But once you're ready to go live or need to scale, you’ll
likely need to consider a paid solution for production or higher volume.
11/11