Sending emails in Node.js applications is achieved using Nodemailer, an open-source library that connects to SMTP (Simple Mail Transfer Protocol) servers or third-party email providers (SendGrid, AWS SES, Mailgun).
flowchart LR
A["Node.js Application"] -->|"nodemailer.createTransport(config)"| B["SMTP Transporter"]
B -->|"transporter.sendMail(options)"| C["SMTP Mail Gateway / Relays"]
C -->|"Delivers Message"| D["Recipient Inbox"]
import nodemailer from 'nodemailer';
// 1. Configure SMTP Transporter
const transporter = nodemailer.createTransport({
host: 'smtp.ethereal.email', // Test SMTP Host
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: '[email protected]',
pass: 'smtp_password_secret'
}
});
// 2. Define Transactional Mail Options
async function sendWelcomeEmail(recipientEmail, recipientName) {
const mailOptions = {
from: '"Developer Portal" <[email protected]>',
to: recipientEmail,
subject: 'Welcome to Kodersolution Platform!',
text: `Hello ${recipientName},
Thank you for registering your developer account.`,
html: `
<div style="font-family: sans-serif; background-color: #0f172a; color: #f8fafc; padding: 20px;">
<h2 style="color: #38bdf8;">Welcome, ${recipientName}!</h2>
<p>We are excited to have you join our developer community platform.</p>
<a href="https://kodersolution.com/dashboard" style="background-color: #0284c7; color: white; padding: 10px 15px; text-decoration: none; border-radius: 5px;">Access Dashboard</a>
</div>
`
};
try {
const info = await transporter.sendMail(mailOptions);
console.log(`Email dispatched successfully! Message ID: ${info.messageId}`);
} catch (error) {
console.error('Failed to send email:', error.message);
}
}
// Execution
sendWelcomeEmail('[email protected]', 'Alex Developer');
.env environment variables accessed via process.env.text parameter alongside html for screen reader accessibility and mail client compatibility.Write down the key configuration properties required inside nodemailer.createTransport() to connect to an SMTP server securely.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.