簡體   English   中英

帶有 Gmail 和 NodeJS 的 Nodemailer

[英]Nodemailer with Gmail and NodeJS

我嘗試使用 nodemailer 來實現使用 NodeJS 的聯系表單,但它只適用於本地,它不適用於遠程服務器......

我的錯誤信息:

[website.fr-11 (out) 2013-11-09T15:40:26] { [AuthError: Invalid login - 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvlX
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 V-dFQLgb7aRCYApxlOBuha5ESrQEbRXK0iVtOgBoYeARpm3cLZuUS_86kK7yPis7in3dGC
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 N1sqhr3D2IYxHAN3m7QLJGukwPSZVGyhz4nHUXv_ldo9QfqRydPhSvFp9lnev3YQryM5TX
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 XL1LZuJL7zCT5dywMVQyWqqg9_TCwbLonJnpezfBLvZwUyersknTP7L-VAAL6rhddMmp_r
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 A_5pRpA> Please log in via your web browser and then try again.
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787
[website.fr-11 (out) 2013-11-09T15:40:26] 534 5.7.14 54 fr4sm15630311wib.0 - gsmtp]
[website.fr-11 (out) 2013-11-09T15:40:26]   name: 'AuthError',
[website.fr-11 (out) 2013-11-09T15:40:26]   data: '534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvlX\r\n534-5.7.14 V-dFQLgb7aRCYApxlOBuha5ESrQEbRXK0iVtOgBoYeARpm3cLZuUS_86kK7yPis7in3dGC\r\n534-5.7.14 N1sqhr3D2IYxHAN3m7QLJGukwPSZVGyhz4nHUXv_ldo9QfqRydPhSvFp9lnev3YQryM5TX\r\n534-5.7.14 XL1LZuJL7zCT5dywMVQyWqqg9_TCwbLonJnpezfBLvZwUyersknTP7L-VAAL6rhddMmp_r\r\n534-5.7.14 A_5pRpA> Please log in via your web browser and then try again.\r\n534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787\r\n534 5.7.14 54 fr4sm15630311wib.0 - gsmtp',
[website.fr-11 (out) 2013-11-09T15:40:26]   stage: 'auth' }

我的 controller:

exports.contact = function(req, res){
    var name = req.body.name;
    var from = req.body.from;
    var message = req.body.message;
    var to = '*******@gmail.com';
    var smtpTransport = nodemailer.createTransport("SMTP",{
        service: "Gmail",
        auth: {
            user: "******@gmail.com",
            pass: "*****"
        }
    });
    var mailOptions = {
        from: from,
        to: to, 
        subject: name+' | new message !',
        text: message
    }
    smtpTransport.sendMail(mailOptions, function(error, response){
        if(error){
            console.log(error);
        }else{
            res.redirect('/');
        }
    });
}

我通過訪問以下網址解決了這個問題(同時使用我要發送郵件的帳戶連接到谷歌):

https://www.google.com/settings/security/lesssecureapps

在那里我啟用了不太安全的應用程序。

完畢

請參閱 nodemailer 的連接 Gmail 的官方指南:

https://community.nodemailer.com/using-gmail/

-

這樣做后它對我有用:

  1. 啟用不太安全的應用程序 - https://www.google.com/settings/security/lesssecureapps
  2. 暫時禁用驗證碼,以便您可以連接新設備/服務器 - https://accounts.google.com/b/0/displayunlockcaptcha

簡單的解決方案:

var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');

var transporter = nodemailer.createTransport(smtpTransport({
  service: 'gmail',
  host: 'smtp.gmail.com',
  auth: {
    user: 'somerealemail@gmail.com',
    pass: 'realpasswordforaboveaccount'
  }
}));

var mailOptions = {
  from: 'somerealemail@gmail.com',
  to: 'friendsgmailacc@gmail.com',
  subject: 'Sending Email using Node.js[nodemailer]',
  text: 'That was easy!'
};

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

步驟1:

去這里https://myaccount.google.com/lesssecureapps並啟用不太安全的應用程序。 如果這不起作用,那么

第2步

去這里https://accounts.google.com/DisplayUnlockCaptcha並啟用/繼續,然后嘗試。

對我來說,單獨的第 1 步不起作用,所以我不得不進行第 2 步。

我還嘗試刪除 nodemailer-smtp-transport 包,令我驚訝的是它可以工作。 但是當我重新啟動系統時,它給了我同樣的錯誤,所以我不得不去打開不太安全的應用程序(我在工作后禁用了它)。

然后為了好玩,我只是嘗試關閉(不太安全的應用程序)和vola它再次工作!

您應該使用XOAuth2 令牌連接到 Gmail。 不用擔心,Nodemailer 已經知道這一點:

var smtpTransport = nodemailer.createTransport('SMTP', {
    service: 'Gmail',
    auth: {
      XOAuth2: {
        user: smtpConfig.user,
        clientId: smtpConfig.client_id,
        clientSecret: smtpConfig.client_secret,
        refreshToken: smtpConfig.refresh_token,
        accessToken: smtpConfig.access_token,
        timeout: smtpConfig.access_timeout - Date.now()
      }
    }
  };

您需要前往Google Cloud Console注冊您的應用。 然后,您需要檢索您希望使用的帳戶的訪問令牌。 您可以為此使用passportjs

這是它在我的代碼中的樣子:

var passport = require('passport'),
    GoogleStrategy = require('./google_oauth2'),
    config = require('../config');

passport.use('google-imap', new GoogleStrategy({
  clientID: config('google.api.client_id'),
  clientSecret: config('google.api.client_secret')
}, function (accessToken, refreshToken, profile, done) {
  console.log(accessToken, refreshToken, profile);
  done(null, {
    access_token: accessToken,
    refresh_token: refreshToken,
    profile: profile
  });
}));

exports.mount = function (app) {
  app.get('/add-imap/:address?', function (req, res, next) {
    passport.authorize('google-imap', {
        scope: [
          'https://mail.google.com/',
          'https://www.googleapis.com/auth/userinfo.email'
        ],
        callbackURL: config('web.vhost') + '/add-imap',
        accessType: 'offline',
        approvalPrompt: 'force',
        loginHint: req.params.address
      })(req, res, function () {
        res.send(req.user);
      });
  });
};

工作正常:

1-安裝nodemailer ,如果未安裝則打包(輸入cmd): npm install nodemailer

2- 轉到https://myaccount.google.com/lesssecureapps並打開允許不太安全的應用程序

3-編寫代碼:

var nodemailer = require('nodemailer');

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

const mailOptions = {
    from: 'any@any.com', // sender address
    to: 'true@true.com', // list of receivers
    subject: 'test mail', // Subject line
    html: '<h1>this is a test mail.</h1>'// plain text body
};

transporter.sendMail(mailOptions, function (err, info) {
    if(err)
        console.log(err)
    else
        console.log(info);
})

4-享受!

我有同樣的問題。 在我的 Google 安全設置中允許“安全性較低的應用程序”使其工作!

同樣的問題也發生在我身上。 我在 localhost 上測試了我的系統,然后部署到服務器(位於不同的國家),然后當我在生產服務器上嘗試系統時,我看到了這個錯誤。 我嘗試了這些來修復它:

  1. https://www.google.com/settings/security/lesssecureapps啟用它,但它不是我的解決方案
  2. https://g.co/allowaccess我允許在有限的時間內從外部訪問,這解決了我的問題。

上述解決方案都不適合我。 我使用了NodeMailer 文檔中存在的代碼。 它看起來像這樣:

let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
        type: 'OAuth2',
        user: 'user@example.com',
        serviceClient: '113600000000000000000',
        privateKey: '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBg...',
        accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x',
        expires: 1484314697598
    }
}); 

我發現Greg T 的回答中提到的這篇文章中描述的最簡單的方法是創建一個應用程序密碼,該密碼在為帳戶打開 2FA 后可用。

myaccount.google.com > 登錄和安全 > 登錄 Google > 應用密碼

這為您提供了該帳戶的備用密碼,然后您只需將 nodemailer 配置為普通的 SMTP 服務。

var smtpTransport = nodemailer.createTransport({
    host: "smtp.gmail.com",
    port: 587,
    auth: {
        user: "username@gmail.com",
        pass: "app password"
    }
});

雖然 Google 推薦 Oauth2 作為最佳選擇,但此方法很簡單,並且尚未在此問題中提及。

額外提示:我還發現您可以將您的應用程序名稱添加到“發件人”地址,並且 GMail 不會像您嘗試使用其他地址那樣僅將其替換為帳戶電子郵件。 IE。

from: 'My Pro App Name <username@gmail.com>'

嘗試在您的 gmail 帳戶中禁用驗證碼; 可能是根據請求者的 IP 地址觸發的。 請參閱: 如何將 GMail 用作免費 SMTP 服務器並克服驗證碼

對我來說,使用端口和安全性以這種方式工作(我在沒有安全設置的情況下使用 PHP 從 gmail 發送電子郵件時遇到問題)

我希望能幫助某人。

var sendEmail = function(somedata){
  var smtpConfig = {
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL, 
                  // you can try with TLS, but port is then 587
    auth: {
      user: '***@gmail.com', // Your email id
      pass: '****' // Your password
    }
  };

  var transporter = nodemailer.createTransport(smtpConfig);
  // replace hardcoded options with data passed (somedata)
  var mailOptions = {
    from: 'xxxx@gmail.com', // sender address
    to: 'yyyy@gmail.com', // list of receivers
    subject: 'Test email', // Subject line
    text: 'this is some text', //, // plaintext body
    html: '<b>Hello world ✔</b>' // You can choose to send an HTML body instead
  }

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

exports.contact = function(req, res){
   // call sendEmail function and do something with it
   sendEmail(somedata);
}

此處列出了所有配置(包括示例)

它是使用 createTransport 中nodemailer-smtp-transport模塊解決的。

var smtpTransport = require('nodemailer-smtp-transport');

var transport = nodemailer.createTransport(smtpTransport({
    service: 'gmail',
    auth: {
        user: '*******@gmail.com',
        pass: '*****password'
    }
}));

許多答案建議允許安全性較低的應用程序,老實說這不是一個干凈的解決方案。

相反,您應該生成一個專用於此用途的應用程序密碼

  1. 登錄您的 Google 帳戶
  2. 安檢
  3. 登錄 Google下啟用兩步驗證
  4. Signing in to Google下,點擊App passwords
  5. 您現在將生成一個新密碼。 選擇應用程序作為郵件和設備作為其他(自定義名稱)並命名。
  6. 保存應用密碼

您現在可以使用此應用程序密碼代替您的登錄密碼。

如果你使用 Express, express-mailer很好地包裝nodemailer並且非常易於使用:

//# config/mailer.js    
module.exports = function(app) {
  if (!app.mailer) {
    var mailer = require('express-mailer');
    console.log('[MAIL] Mailer using user ' + app.config.mail.auth.user);
    return mailer.extend(app, {
      from: app.config.mail.auth.user,
      host: 'smtp.gmail.com',
      secureConnection: true,
      port: 465,
      transportMethod: 'SMTP',
      auth: {
        user: app.config.mail.auth.user,
        pass: app.config.mail.auth.pass
      }
    });
  }
};

//# some.js
require('./config/mailer.js)(app);
app.mailer.send("path/to/express/views/some_view", {
  to: ctx.email,
  subject: ctx.subject,
  context: ctx
}, function(err) {
  if (err) {
    console.error("[MAIL] Email failed", err);
    return;
  }
  console.log("[MAIL] Email sent");
});

//#some_view.ejs
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title><%= subject %></title>
  </head>
  <body>
  ... 
  </body>
</html>

出於某種原因,即使是驗證碼,只允許不太安全的應用程序配置對我也不起作用。 我不得不做另一個步驟,即啟用 IMAP 配置:

從谷歌的幫助頁面: https ://support.google.com/mail/answer/7126229?p=WebLoginRequired&visit_id=1-636691283281086184-1917832285&rd=3#cantsignin

  • 在右上角,單擊設置設置。
  • 單擊設置。
  • 單擊轉發和 POP/IMAP 選項卡。
  • 在“IMAP 訪問”部分中,選擇啟用 IMAP。
  • 單擊保存更改。

您所有的代碼都可以,只剩下剩下的就是轉到鏈接https://myaccount.google.com/security

並繼續向下滾動,你會發現允許不太安全的應用程序:打開並保持打開,你會發現沒有錯誤。

只需添加“主機”就可以了。

host: 'smtp.gmail.com'

然后通過單擊下面的鏈接啟用“lesssecureapps”

https://myaccount.google.com/lesssecureapps

exports.mailSend = (res, fileName, object1, object2, to, subject,   callback)=> {
var smtpTransport = nodemailer.createTransport('SMTP',{ //smtpTransport
host: 'hostname,
port: 1234,
secureConnection: false,
//   tls: {
//     ciphers:'SSLv3'
// },
auth: {
  user: 'username',
  pass: 'password'
}

});
res.render(fileName, {
info1: object1,
info2: object2
}, function (err, HTML) {

smtpTransport.sendMail({
  from: "mail@from.com",
  to: to,
  subject: subject,
  html: HTML
}
  , function (err, responseStatus) {
      if(responseStatus)
    console.log("checking dta", responseStatus.message);
    callback(err, responseStatus)
  });
});
}

您必須在代碼中添加 secureConnection 類型。

我使用的是舊版本的 nodemailer 0.4.1 並且遇到了這個問題。 我更新到 0.5.15,現在一切正常。

編輯 package.json 以反映更改

npm install

只需參加這些: 1-在您重新啟動客戶端瀏覽器之前不接受允許低級別電子郵件的 Gmail 身份驗證 2-如果您想使用 nodemailer 發送電子郵件並且您不想使用 xouath2 協議,您應該寫為 secureconnection:false 如下所示

const routes = require('express').Router();
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');



routes.get('/test', (req, res) => {
  res.status(200).json({ message: 'test!' });
});

routes.post('/Email', (req, res) =>{

    var smtpTransport = nodemailer.createTransport({
        host: "smtp.gmail.com",
        secureConnection: false,
        port: 587,
        requiresAuth: true,
        domains: ["gmail.com", "googlemail.com"],
        auth: {
            user: "your gmail account", 
            pass: "your password*"
        }
});  

  var mailOptions = {
      from: 'from@gmail.com',
      to:'to@gmail.com',
      subject: req.body.subject,
      //text: req.body.content,
      html: '<p>'+req.body.content+' </p>'
  };

  smtpTransport.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log('Error while sending mail: ' + error);
    } else {
        console.log('Message sent: %s', info.messageId);
    }
    smtpTransport.close();
});  

})

module.exports = routes;

首先安裝nodemailer

npm install nodemailer  --save

導入到js文件

const nodemailer = require("nodemailer");

const smtpTransport = nodemailer.createTransport({
    service: "Gmail",
    auth: {
        user: "example@gmail.com",
        pass: "password"
    },
    tls: {
        rejectUnauthorized: false
    }
});






 const mailOptions = {
        from: "example@gmail.com",
        to: sending@gmail.com,
        subject: "Welcome to ",
        text: 'hai send from me'.
    };


    smtpTransport.sendMail(mailOptions, function (error, response) {
        if (error) {
            console.log(error);
        }
        else {
            console.log("mail sent");
        }
    });

在我的應用程序中工作

您可能需要在您的 Gmail 帳戶中“允許不太安全的應用程序”(它一直在底部)。 您可能還需要“允許訪問您的 Google 帳戶”。 您可能還需要“允許訪問您的 Google 帳戶”。

這是我的Nodemailer 配置,經過一些研究后工作。

第 1 步:啟用 lesssecureapp

https://www.google.com/settings/security/lesssecureapps 

第 2 步:Gmail 的 Nodemailer 配置

設置傳輸器:傳輸器將成為可以發送郵件的對象。 它是傳輸配置對象、連接 URL 或傳輸插件實例

let transporter = nodemailer.createTransport({
    service: 'gmail',                              // the service used
    auth: {
        user: process.env.EMAIL_FROM,              // authentication details of sender, here the details are coming from .env file
        pass: process.env.EMAIL_FROM_PASSWORD,
    },
});

寫消息

const message = {
    from: 'myemail@gmail.com',                         // sender email address
    to: "receiver@example.com, receiver2@gmail.com",   // reciever email address
    subject: `The subject goes here`,
    html: `The body of the email goes here in HTML`,
    attachments: [
    {
      filename: `${name}.pdf`,
      path: path.join(__dirname, `../../src/assets/books/${name}.pdf`),
      contentType: 'application/pdf',
    },
  ],

發送郵件

transporter.sendMail(message, function (err, info) {
    if (err) {                                            // if error
        console.log(err);
    } else {
        console.log(info);                                // if success
    }
});

在生產環境中運行 Vercel lambda 時,我也遇到了 nodemailer 電子郵件發送的問題。

在我的情況下解決它的是等待 sendMail Promise 解決。

我還添加了 nodemailer-smtp-transport 就像在這個線程中建議的那樣,但我認為它沒有什么不同。

這是我的整個功能:

const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');


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


async function contact(req: any, res: any) {
    try {
        const response = await transporter.sendMail({
            from: '"*** <***gmail.com>', // sender address
            to: "***@gmail.com", // list of receivers
            subject: `***`, // Subject line
            html: `${req.body.message}<br/><br/>${req.body.firstname} ${req.body.lastname} - <b>${req.body.email}</b>`, // html body
        });
    } catch (error: any) {
        console.log(error);
        return res.status(error.statusCode || 500).json({ error: error.message });
    }

    return res.status(200).json({ error: "" });
}

export default contact;

Google 已禁用不太安全的應用程序訪問,以下是在 Nodejs 中使用 Gmail 的新流程

  1. 現在您必須在 Google 中啟用兩步驗證(如何啟用兩步驗證
  2. 您需要生成應用專用密碼。 轉到Google 我的帳戶 > 安全性
  3. 點擊應用密碼 > 選擇其他,您將獲得應用密碼
  4. 您可以使用帶有電子郵件和應用程序密碼的普通 smtp。

gmail 不再支持不太安全的選項。

對於從第三方發送電子郵件,gmail 也不允許使用其用戶密碼

您現在應該使用應用密碼來解決此問題。 希望此鏈接有助於設置您的應用密碼。 https://support.google.com/mail/answer/185833?hl=en

gmail 不再支持這種方法

在此處輸入圖像描述

在此處輸入圖像描述

正如 Yaach 指出的那樣,截至 2022 年 5 月 30 日,Google 不再支持不太安全的應用程序,而是切換到他們自己的Gmail API

這是 Gmail SMTP 和 nodemailer 的示例代碼。

"use strict";
const nodemailer = require("nodemailer");

async function main() {
    let transporter = nodemailer.createTransport({
        host: "smtp.gmail.com",
        transportMethod: "SMTP",
        secureConnection: true,
        port: 465,
        secure: true, // upgrade later with STARTTLS
        auth: {
            user: "yourEmail@gmail.com",
            pass: "Your App  Specific password",
        },
    });

    let info = await transporter.sendMail(
        {
            from: "yourEmail@gmail.com",
            to: "to@gmail.com",
            subject: "Testing Message Message",
            text: "I hope this message gets delivered!",
            html: "<b>Hello world?</b>", // html body
        },
        (err, info) => {
            if (err) {
                console.log(err);
            } else {
                console.log(info.envelope);
                console.log(info.messageId);
            }
        }
    );
}

main();

谷歌不再提供啟用“不太安全”的應用程序。 更好的方法是使用應用程序密碼。 請參閱下面的 scipilot 答案。

我將其發布為答案,因為我仍然沒有足夠的代表發表評論。

還有另一個選項可以使用 SendGrid 進行電子郵件傳遞而不會失敗。 很多時候,Nodemailer 會給出可能經常發生的郵件失敗。

Nodemailer可以在鏈接中找到。

暫無
暫無

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

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