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

如何用Node.js发送邮件?使用Nodemailer遇问题求协助

Fixing Nodemailer Gmail Delivery Issues

Hey there, I’ve dealt with this exact problem a bunch of times—Gmail’s security settings love to throw a wrench in Nodemailer setups. Let’s walk through the most likely fixes for your code:

Gmail blocks regular password logins from apps like Nodemailer unless you’ve enabled two-factor authentication (2FA) and generated an App Password. Here’s how to do it:

  • Open your Google Account’s Security settings
  • Turn on 2FA if you haven’t already
  • Look for the "App Passwords" option (it only appears after 2FA is enabled)
  • Select "Mail" as the app, choose "Other (custom name)" for the device, and generate a 16-character password
  • Replace 'yourpassword' in your code with this generated App Password

2. Switch to Explicit SMTP Configuration

Sometimes relying on the service: 'gmail' shorthand can cause unexpected issues. Try using the full SMTP settings instead:

var transporter = nodemailer.createTransport({
  host: 'smtp.gmail.com',
  port: 587,
  secure: false, // Set to true only if using port 465
  auth: {
    user: 'youremail@gmail.com',
    pass: 'your-generated-app-password' // Use the App Password here
  }
});

3. Check for Specific Error Details

Your current code logs errors, but make sure to note the exact error message if these fixes don’t work. Common issues include:

  • Invalid login: Your username or App Password is incorrect
  • ETIMEDOUT: A network or firewall is blocking the connection to Gmail’s SMTP server
  • Less secure app access blocked: You tried using a regular password without an App Password (Gmail no longer allows this for most accounts)

Modified Working Example

Here’s your code updated with the recommended fixes:

var nodemailer = require('nodemailer');

// Explicit SMTP configuration for reliability
var transporter = nodemailer.createTransport({
  host: 'smtp.gmail.com',
  port: 587,
  secure: false,
  auth: {
    user: 'youremail@gmail.com',
    pass: 'your-generated-app-password' // Replace with your App Password
  }
});

var mailOptions = {
  from: 'youremail@gmail.com',
  to: 'myfriend@yahoo.com',
  subject: 'Sending Email using Node.js',
  text: 'That was easy!'
};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.error('Email failed to send:', error); // More descriptive error log
  } else {
    console.log('Email sent successfully:', info.response);
  }
});

One last thing: If you still get blocked, check your Google Account’s "Recent security activity"—Gmail might have flagged the login attempt, and you’ll need to approve it manually.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 14:28:13