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

Node.js与Express项目中使用Nodemailer发送邮件的实现方法及ECONNECTION错误排查咨询

Hey there! Let's start by fixing that ECONNECTION error you're seeing with Nodemailer, then walk through a complete setup for sending emails in your Express project.

First: What's Causing That ECONNECTION Error?

The error {"errno": -4078, "code": "ECONNECTION", ... port: 25} happens because Nodemailer defaults to trying to connect to a local SMTP server at 127.0.0.1:25, but you don't have a local SMTP service running on your machine. That's totally normal—most developers use third-party SMTP services (like Gmail, SendGrid, or Outlook) instead of setting up their own local server.

Step-by-Step Setup for Nodemailer in Express

Let's build a working implementation from scratch. We'll use Gmail as an example (but you can swap in other services easily).

1. Install Dependencies

First, add Nodemailer to your project:

npm install nodemailer

2. Create a Reusable Mailer Module

Make a new file mailer.js in your project to wrap Nodemailer's configuration—this keeps your code clean and reusable:

const nodemailer = require('nodemailer');

// Create an SMTP transporter using your email service
const transporter = nodemailer.createTransport({
  service: 'gmail', // Replace with 'outlook', 'yahoo', or custom SMTP details
  auth: {
    user: 'your-email@gmail.com', // Your full email address
    pass: 'your-app-password-or-email-password' // Important note below!
  }
});

// Wrapper function to send emails
const sendEmail = async (mailOptions) => {
  try {
    const deliveryInfo = await transporter.sendMail(mailOptions);
    console.log('Email sent successfully:', deliveryInfo.response);
    return deliveryInfo;
  } catch (err) {
    console.error('Failed to send email:', err);
    throw err; // Pass error up to handle in your route
  }
};

module.exports = sendEmail;

Gmail Users Note: If you have 2FA enabled on your Google account, you can't use your regular password here. Instead, create an App Password in your Google Account settings (under Security > App Passwords). If you don't have 2FA enabled, you'll need to allow "less secure apps" (though Google discourages this—2FA + App Password is safer).

3. Add an Express Route for Sending Emails

Create a route (e.g., in routes/email.js) to handle email send requests:

const express = require('express');
const sendEmail = require('../mailer');
const router = express.Router();

// POST endpoint to send an email
router.post('/send', async (req, res) => {
  try {
    // Get email details from the request body
    const { to, subject, plainText, htmlContent } = req.body;

    const mailOptions = {
      from: 'your-email@gmail.com', // Must match the email in your transporter
      to: to, // Can be multiple emails separated by commas
      subject: subject,
      text: plainText, // Plain text fallback for email clients that don't support HTML
      html: htmlContent // Optional: HTML formatted content
    };

    await sendEmail(mailOptions);
    res.status(200).json({ message: 'Email sent successfully!' });
  } catch (err) {
    res.status(500).json({ 
      message: 'Failed to send email', 
      error: err.message 
    });
  }
});

module.exports = router;

4. Register the Route in Your Express App

Update your main app.js (or server.js) to use the new route:

const express = require('express');
const emailRouter = require('./routes/email');
const app = express();

// Parse JSON request bodies (required to read data from POST requests)
app.use(express.json());

// Mount the email route under /api/email
app.use('/api/email', emailRouter);

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
Alternative SMTP Service Examples

If you don't want to use Gmail, here are quick configs for other popular services:

SendGrid

const transporter = nodemailer.createTransport({
  host: 'smtp.sendgrid.net',
  port: 587,
  secure: false, // Use true for port 465
  auth: {
    user: 'apikey',
    pass: 'your-sendgrid-api-key'
  }
});

Outlook/Hotmail

const transporter = nodemailer.createTransport({
  service: 'outlook',
  auth: {
    user: 'your-email@outlook.com',
    pass: 'your-outlook-password'
  }
});

内容的提问来源于stack exchange,提问作者محمد هاشمی

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 14:02:30