Sending Emails with Nodemailer
Send emails from Node.js with Nodemailer. Learn SMTP and email templates.
Sending Emails with Nodemailer
Why Send Emails from Node.js?
Common use cases: - Welcome emails after signup - Password reset links - Order confirmations - Notifications - Reports
Setup
```bash npm install nodemailer ```
```javascript const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransporter({ host: 'smtp.gmail.com', port: 587, secure: false, auth: { user: 'your-email@gmail.com', pass: 'your-app-password' } }); ```
**Note:** Use App Password, not regular Gmail password.
Send Basic Email
```javascript async function sendEmail() { await transporter.sendMail({ from: '"Your Name" <your-email@gmail.com>', to: 'recipient@example.com', subject: 'Hello from Node.js', text: 'Plain text content', html: '<b>HTML content</b>' }); } ```
Real Example: Welcome Email
```javascript async function sendWelcomeEmail(user) { const html = ` <h1>Welcome, ${user.name}!</h1> <p>Thank you for signing up.</p> <a href="https://example.com/verify?token=${user.verifyToken}"> Verify Email </a> `; await transporter.sendMail({ from: '"MyApp" <noreply@example.com>', to: user.email, subject: 'Welcome to MyApp', html }); } ```
Real Example: Password Reset
```javascript async function sendPasswordReset(user, resetToken) { const resetURL = `https://example.com/reset-password?token=${resetToken}`; const html = ` <h2>Password Reset Request</h2> <p>Click the link below to reset your password:</p> <a href="${resetURL}">Reset Password</a> <p>This link expires in 1 hour.</p> `; await transporter.sendMail({ to: user.email, subject: 'Password Reset', html }); } ```
Queue Emails (Production)
```javascript const Queue = require('bull'); const emailQueue = new Queue('email');
async function queueEmail(to, subject, html) { await emailQueue.add({ to, subject, html }); }
emailQueue.process(async (job) => { const { to, subject, html } = job.data; await transporter.sendMail({ from: 'noreply@example.com', to, subject, html }); });
await queueEmail('user@example.com', 'Welcome', '<h1>Welcome!</h1>'); ```
**Why queue?** Don't block HTTP response waiting for email to send.
Key Takeaway
Use Nodemailer for sending emails. Queue emails in production for reliability. Use HTML templates for better design. Always handle errors. Consider services like SendGrid for high volume.