簡體   English   中英

使用 nodemailer 通過 Node.js 發送 email 無效

[英]Sending email via Node.js using nodemailer is not working

我已經在本地 ( http://localhost:8080 ) 設置了一個基本的 NodeJS 服務器(使用 nodemailer 模塊),這樣我就可以測試服務器是否真的可以發送電子郵件。

如果我正確理解 SMTP 選項(如果我錯了請糾正我),我可以嘗試從我的服務器直接向某人的 email 帳戶發送 email,或者我可以發送 email,仍然使用 Node.js,但是通過實際 email 帳戶(在本例中是我的個人 Gmail 帳戶),即使用 SMTP。此選項要求我通過 NodeJS 遠程登錄該帳戶。

所以在下面的服務器中,我實際上是在嘗試使用 NodeJs 將 email 從我的個人 email 帳戶發送到我的個人 email 帳戶。

這是我的簡單服務器:

var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport("SMTP", {
    service: 'Gmail',
    auth: {
        user: '*my personal Gmail address*',
        pass: '*my personal Gmail password*'
    }
});

var http = require('http');
var httpServer = http.createServer(function (request, response)
{
    transporter.sendMail({
       from: '*my personal Gmail address*',
       to: '*my personal Gmail address*',
       subject: 'hello world!',
       text: 'hello world!'
    });
}).listen(8080);

但是,它不起作用。 我通過谷歌得到了一個 email 說:

Google 帳戶:登錄嘗試被阻止如果這是您您可以切換到 Google 制作的應用程序,例如 Gmail 以訪問您的帳戶(推薦)或在https://www.google.com/settings/security/更改您的設置lesssecureapps使您的帳戶不再受到現代安全標准的保護。

我在 nodemailer GitHub 頁面上找不到上述問題的解決方案。 有人有解決方案/建議嗎?

謝謝: :-)

答案在來自谷歌的消息中。

對於問題的第二部分,以及響應

我實際上只是按照 nodemailer github 頁面中的步驟操作,因此我的代碼中沒有錯誤

我將向您推薦 nodemailer github 頁面,以及這段代碼:

var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
    user: 'gmail.user@gmail.com',
    pass: 'userpass'
}
});

它與您的代碼略有不同,因為您有: nodemailer.createTransport("SMTP" 。刪除 SMTP 參數並且它可以工作(剛剛測試)。另外,為什么將它封裝在 http 服務器中?以下工作:

var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: 'xxx',
        pass: 'xxx'
    }
});

console.log('created');
transporter.sendMail({
from: 'xxx@gmail.com',
  to: 'xxx@gmail.com',
  subject: 'hello world!',
  text: 'hello world!'
});

過時:JSON 文件輸出中不再存在 refreshToken 和 accessToken

對於那些真正想要使用 OAuth2 / 不想讓應用程序“不那么安全”的人,您可以通過

  1. 谷歌 API 控制台搜索“Gmail API”並點擊“啟用”
  2. 按照https://developers.google.com/gmail/api/quickstart/nodejs 中的步驟操作。 在 quickstart.js 文件中,將快速入門 js 中的SCOPES var 從['https://www.googleapis.com/auth/gmail.readonly']更改為['https://mail.google.com/']按照https://nodemailer.com/smtp/oauth2/ 上的故障排除中的建議提供的文件
  3. 按照(2)中的步驟操作后,生成的 JSON 文件將包含acessTokenOAuth2 示例中所需的acessTokenrefreshTokenexpires屬性

這樣您就可以使用 OAuth2 身份驗證,如下所示

let transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        type: 'OAuth2',
        user: 'user@example.com',
        clientId: '000000000000-xxx0.apps.googleusercontent.com',
        clientSecret: 'XxxxxXXxX0xxxxxxxx0XXxX0',
        refreshToken: '1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx',
        accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x',
        expires: 1484314697598
    }
});

而不是以明文形式存儲您的 Gmail 密碼並降低您帳戶的安全性。

我只是將我的域設置為:smtp.gmail.com 並且它有效。 我正在使用 VPS Vultr。

編碼:

const nodemailer = require('nodemailer');
const ejs = require('ejs');
const fs = require('fs');

let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
        user: 'xxx@gmail.com',
        pass: 'xxx'
    }
});

let mailOptions = {
    from: '"xxx" <xxx@gmail.com>',
    to: 'yyy@gmail.com',
    subject: 'Teste Templete ✔',
    html: ejs.render( fs.readFileSync('e-mail.ejs', 'utf-8') , {mensagem: 'olá, funciona'})
};

transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message %s sent: %s', info.messageId, info.response);
});

我的 ejs 模板(e-mail.ejs):

<html>
    <body>
        <span>Esse é um templete teste</span>
        <p> gerando com o EJS - <%=mensagem%> </p>
    </body>
</html>

確保:

  • 安裝 ejs: npm install ejs --save
  • 安裝 nodemailer: npm install nodemailer --save
  • ping smtp.gmail.com 有效: ping smtp.gmail.com
  • 將 xxx@gmail.com 更改為您的 Gmail 電子郵件
  • 將 yyy@gmail.com 更改為您要發送電子郵件的電子郵件
  • 啟用安全性較低的應用
  • 暫時禁用驗證碼

祝你今天過得愉快 ;)

雖然上述答案確實有效,但我想指出您可以通過以下兩個步驟來降低 Gmail 的安全性。

第1步

Google 帳戶:登錄嘗試被阻止 如果是您您可以切換到 Google 制作的應用程序(例如 Gmail)來訪問您的帳戶(推薦)或在https://www.google.com/settings/security/更改您的設置lesssecureapps使您的帳戶不再受現代安全標准的保護。

第2步

除了啟用允許不太安全的應用程序外,您可能還需要導航到https://accounts.google.com/DisplayUnlockCaptcha並單擊繼續。

您只需要 google auth 的 App 密碼,然后在您的代碼中替換您的 google 密碼。 去這里https://myaccount.google.com/apppasswords

示例代碼:

const nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
    service: "Gmail",
    auth: {
      user: 'example@gmail.com',
      pass: 'app password here'
    }
  });
transporter.sendMail(option, function(error, info){
    if (error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }
});

截屏

出於調試目的,實現一個顯示錯誤消息(如果有的話)的回調函數(他們從來沒有在 nodemailer github 頁面上做)是很方便的。

transporter.sendMail({
    from: from,
    to: to,
    subject: subject,
    html: text
}, function(err){
    if(err)
        console.log(err);
})

它幫助我解決了我的問題......結果是新版本無法正常工作:

“看起來 nodemailer 1.0 有重大變化,所以必須使用 0.7: http ://www.nodemailer.com/

截至 2015 年 12 月 17 日在 nodemailer 上發布的消息:

不要將 Nodemailer 從 0.7 或更低版本升級到 1.0,因為存在重大更改。 只要你願意,你可以繼續使用 0.7 分支。 請參閱此處0.7 的文檔。”

我在這里找到了這個答案

並安裝 smtp 模塊作為依賴項:

npm install smtp

var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  type: "SMTP",
  host: "smtp.gmail.com",
  secure: true,
  auth: {
    user: 'writeYourGmailId@gmail.com',
    pass: 'YourGmailPassword'
  }
});

var mailOptions = {
  from: 'xyz.khan704@gmail.com',
  to: 'azran.khan704@gmail.com',
  subject: 'Sending Email to test Node.js nodemailer',
  text: 'That was easy to test!'
};

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

轉到https://myaccount.google.com/lesssecureapps並將其更改為ON,因為某些應用和設備使用安全性較低的登錄技術,這會使您的帳戶更容易受到攻擊。 您可以關閉這些應用程序的訪問權限(我們建議您這樣做),或者如果您想使用它們而不顧風險打開訪問權限。

試試這個代碼對我有用。

var http = require('http');
var nodemailer = require('nodemailer');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});

  var fromEmail = 'akarthi@xyz.com';
  var toEmail = 'akarthi@xyz.com';

  var transporter = nodemailer.createTransport({
    host: 'domain',
    port: 587,
    secure: false, // use SSL
    debug: true,
      auth: {
        user: 'fromEmail@xyz.com',
        pass: 'userpassword'
      }
  });
   transporter.sendMail({
      from: fromEmail,
      to: toEmail,
      subject: 'Regarding forget password request',
      text: 'This is forget password response from your app',
      html: '<p>Your password is <b>sample</b></p>'
  }, function(error, response){
      if(error){
          console.log('Failed in sending mail');
          console.dir({success: false, existing: false, sendError: true});
          console.dir(error);
          res.end('Failed in sending mail');
      }else{
          console.log('Successful in sending email');
          console.dir({success: true, existing: false, sendError: false});
          console.dir(response);
          res.end('Successful in sending email');
      }
  });
}).listen(8000);
console.log('Server listening on port 8000');

回復:

Successful in sending email
{ success: true, existing: false, sendError: false }
{ accepted: [ 'akarthi@xyz.com' ],
  rejected: [],
  response: '250 2.0.0 uAMACW39058154 Message accepted for delivery',
  envelope: 
   { from: 'akarthi@xyz.com',
     to: [ 'akarthi@xyz.com' ] },
  messageId: '1479809555147-33de4987-29d605fa-6ee150f1@xyz.com' }

在此處輸入圖片說明

添加到 xShirase 答案僅提供啟用的屏幕截圖。 還要安全地確認之前的嘗試是由您發起的。

Xshirase 值得所有人點贊。我只是顯示屏幕截圖。

不應該再使用 gmail密碼了!

最近谷歌提供了一種在第 3 方應用程序或 API 中使用的新方法。 您需要使用App Password而不是 gmail 密碼。 但是要創建它,您需要在您的谷歌帳戶中啟用兩步驗證模式:

您可以在此處找到步驟: https://support.google.com/mail/answer/185833?hl=en

這是使用 gmail 發送 email 的最佳方式

const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '******@gmail.com',
        pass: '**********',
    },
});

使用來自谷歌的兩次身份驗證=>安全=>應用密碼並填寫一些東西獲取應用密碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM