You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何基于Node.js搭建SMTP服务器实现网站定时/条件触发自动邮件?

Hey there! Let's break this down step by step since you're new to this space—no worries, we'll get you sorted with a solid plan for your Node.js app to send automated emails.

1. First: Choose Between Self-Hosted SMTP or Third-Party Service

Before diving into code, let's pick the right foundation:

  • Third-party services (highly recommended for beginners): Services like SendGrid, Mailgun, or Postmark handle all the messy stuff like IP reputation, anti-spam rules, and server maintenance. You just need to sign up, get an API key/SMTP credentials, and plug them into your Node.js app. This way you avoid the headache of configuring and maintaining your own server, which is way harder than it sounds for someone new.
  • Self-hosted SMTP (only if you have specific reasons): If you must host your own, tools like Postfix (for Linux servers) or hMailServer (Windows) are popular options. But be warned: you'll need to set up SPF/DKIM/DMARC records, maintain IP reputation, and handle deliverability issues—this is a long-term commitment, not a quick setup.
2. Node.js Email Sending with Nodemailer

The go-to library for sending emails in Node.js is nodemailer—it's straightforward and works with both third-party SMTP and self-hosted servers.

First, install it via npm:

npm install nodemailer

Here's a basic example to send an email:

const nodemailer = require('nodemailer');

// Create a transporter with your SMTP credentials
const transporter = nodemailer.createTransport({
  host: 'your-smtp-host.com', // e.g., smtp.sendgrid.net for SendGrid
  port: 587, // 587 is for STARTTLS, 465 for SSL
  secure: false, // set to true if using port 465
  auth: {
    user: 'your-smtp-username', // or API key username for third-party services
    pass: 'your-smtp-password' // or API key
  }
});

// Function to send an email
async function sendEmail(to, subject, html) {
  try {
    const info = await transporter.sendMail({
      from: '"Your Company" <noreply@yourcompany.com>', // sender address
      to: to, // list of receivers
      subject: subject, // Subject line
      html: html // html body
    });
    console.log('Email sent: ' + info.messageId);
  } catch (error) {
    console.error('Error sending email:', error);
  }
}

// Test it out
sendEmail('user@example.com', 'Test Automated Email', '<p>Hello from your Node.js app!</p>');
3. Automate Emails: Scheduled vs Conditional Triggers

Now let's make this run automatically based on your needs:

Scheduled Emails (Daily/Weekly)

Use a cron job library like node-cron or node-schedule to trigger emails at specific times. Let's use node-cron as an example:

Install it:

npm install node-cron

Example code for daily and weekly triggers:

const cron = require('node-cron');

// Send daily at 9 AM
cron.schedule('0 9 * * *', () => {
  console.log('Sending daily email...');
  sendEmail('daily-recipients@example.com', 'Daily Update', '<p>Here\'s your daily company update!</p>');
}, {
  timezone: 'Asia/Shanghai' // Set your timezone
});

// Send every Monday at 10 AM
cron.schedule('0 10 * * 1', () => {
  console.log('Sending weekly email...');
  sendEmail('weekly-recipients@example.com', 'Weekly Report', '<p>Here\'s your weekly company roundup!</p>');
}, {
  timezone: 'Asia/Shanghai'
});

Conditional Triggers

If you need to send emails based on specific conditions (e.g., a user completes an action, a database record meets criteria), you can trigger the sendEmail function directly in your app logic:

// Example: Trigger when a user signs up
app.post('/signup', async (req, res) => {
  // ... your signup logic (save user to DB, etc.) ...
  
  // Send welcome email
  await sendEmail(req.body.email, 'Welcome to Our Platform!', '<p>Thanks for signing up—we\'re glad to have you!</p>');
  
  res.send('Signup successful!');
});

// Example: Check database hourly for pending orders and send reminders
cron.schedule('0 * * * *', async () => {
  // Fetch pending orders from your database
  const pendingOrders = await db.orders.find({ status: 'pending' });
  
  if (pendingOrders.length > 0) {
    for (const order of pendingOrders) {
      await sendEmail(order.customerEmail, 'Reminder: Your Order is Pending', `<p>Hi there! Your order #${order.id} is still pending. Please complete payment soon.</p>`);
    }
  }
});
4. Pro Tips for Beginners
  • Keep credentials secure: Never hardcode your SMTP password/API key in your code. Use environment variables (with dotenv library) to store sensitive data. Install dotenv with npm install dotenv, create a .env file with your credentials, and load them with require('dotenv').config().
  • Test first: Always send test emails to your own address before sending to customers to avoid formatting issues or deliverability problems.
  • Log everything: Add detailed logs for email sends and errors—this will save you a ton of time when troubleshooting.
  • Check deliverability: For third-party services, they usually provide dashboards to track if emails are being delivered, marked as spam, etc. For self-hosted, use tools to check your SPF/DKIM records and IP reputation.

内容的提问来源于stack exchange,提问作者LittleOldMe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:55:46