首页 > 解决方案 > Nodemailer OAUTH Gmail 连接(错误:连接 ETIMEDOUT 74.125.140.108:465)

问题描述

我正在尝试使用 OAUTH 2.0 使用 Nodemailer 使用 Gmail API 发送电子邮件

我启用了 Gmail API,并且我有 clientId、clientSecret、refreshToken 和 accessToken(refreshtoken 和 accesstoken 取自 developer.google.com/oauthplayground),因为这些都是 OAUTH 工作所必需的。

我已经遵循了每一个详细的表格(https://nodemailer.com/smtp/oauth2/#examples)但我收到了以下错误

{ Error: connect ETIMEDOUT 74.125.140.108:465
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)
  errno: 'ETIMEDOUT',
  code: 'ESOCKET',
  syscall: 'connect',
  address: '74.125.140.108',
  port: 465,
  command: 'CONN' }

但是当我使用普通用户名和密码时有一个问题,没有连接超时错误,因为我已经启用了不太安全的应用程序访问表单(https://myaccount.google.com/lesssecureapps),所以使用发送电子邮件没有错误普通的用户名和密码,但这不是一个好方法,所以 OAUTH 是解决方案

这是我的代码供您检查(它是一个快速应用程序)在http://localhost:3000上运行的开发中运行

var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
service: 'gmail',
auth: {
  type: 'OAuth2',
  user: 'mygmailaddress@gmail.com',
  clientId: 'clientID',
  clientSecret: 'clientSecret',
  refreshToken: 'refresh token obtained from https://developers.google.com/oauthplayground',
  accessToken: 'access token also obtained from https://developers.google.com/oauthplayground'
}
});
var mailOptions = {
    from: 'me <myemailaddress@gmail.com>',
    to: '',
    subject: 'Subject ',
    text: 'Some thing',
  };

  transporter.sendMail(mailOptions, (error, response) => {
    if(error){
        console.log(error);   // Always giving Error: connect ETIMEDOUT 74.125.140.108:465
    } else {
        console.log(response);
    }
});

它甚至不会尝试登录,因为当登录失败时,它会给出错误凭据的错误(使用普通用户名和密码进行检查)

*注意请不要将此问题标记为重复,因为我已经检查了几乎所有其他问题和答案,但没有任何工作有人说这是因为防火墙设置我也检查过但没有工作那么问题是什么以及如何解决它

标签: oauth-2.0smtpgmail-apinodemailersmtp-auth

解决方案


您的端口号对于 gmail 是错误的。将此格式用于 gmail

const nodeMailer = require('nodemailer');

let transporter = nodeMailer.createTransport({
    host: "smtp.gmail.com",
    port: 587,
    secure: false, // true for 587, false for other ports
    requireTLS: true,
    auth: {
        user: your email, 
        pass: your password, 
    },
});

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

transporter.sendMail(mailOptions, function(error, info){
    if (error) {
       console.log(error);
    } else {
        console.log('Email sent: ' + info.response);
    }
});

推荐阅读