如何用Node.js发送邮件?使用Nodemailer遇问题求协助
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:
1. Use an App Password (The Recommended Fix)
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 incorrectETIMEDOUT: A network or firewall is blocking the connection to Gmail’s SMTP serverLess 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

