Gmail 및 NodeJS를 사용하는 Nodemailer


110

NodeJS를 사용하여 연락처 양식을 구현하기 위해 nodemailer를 사용하려고하지만 로컬에서만 작동하며 원격 서버에서는 작동하지 않습니다.

내 오류 메시지 :

[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' }

내 컨트롤러 :

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('/');
        }
    });
}

14
google.com/accounts/DisplayUnlockCaptcha (가시성을 위해 아래에 좋은 댓글 작성자가 게시 함). 한 번만 액세스를 허용하고 nodemailer가 자동으로 로그인하도록합니다.
— laggingreflex

3
Gmail에서 nodemailer를 사용을 통해 메일을 보내도록 모든 노력 후, 다음과 같은 설정이 .. 나를 위해 일한
— faizanjehangir

답변:


136

다음 URL로 이동하여이 문제를 해결했습니다 (메일을 보내려는 계정으로 Google에 연결되어있는 동안).

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

보안 수준이 낮은 앱을 활성화했습니다.

끝난


1
잘 했어! 그것이 나는 그것이 좋은 생각이라고 생각하지 않지만, 노력하고 있습니다 ... 내가 처음으로 email..Thx있어
— ackuser

이것을 활성화하지 않으면 로컬 환경에서도 작동하지 않습니다. 그는 그것이 로컬 환경에서 작동하고 원격 서버에서는 작동하지 않는다고 분명히 언급했습니다. thaat의 해결책은 무엇입니까?
— Adithya Sai

Gmail 계정에서 2FA의 인증이있는 경우이 당신을 도울 수 없습니다
— 사샤 로마노프

63

Gmail 연결에 대한 nodemailer의 공식 가이드를 참조하세요.

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

-

이것을 한 후에 나를 위해 작동합니다.

  1. 보안 수준이 낮은 앱 사용-https: //www.google.com/settings/security/lesssecureapps
  2. - 사용 안 함 보안 문자 일시적 그래서 당신은 새로운 장치 / 서버에 연결할 수 있습니다 https://accounts.google.com/b/0/displayunlockcaptcha을

18
2 번은 내 고통을 해결했습니다. Google 계정 설정에서 링크를 찾을 수 없습니다. 감사합니다!
— programstinator

1
여기도 마찬가지입니다. 나는 이전에 # 1을했고 localhost에서 작업하는 이메일을 받고 프로덕션으로 이동했지만 아무것도 작동하지 않았습니다. # 2 프로덕션 문제를 해결했습니다. 감사합니다
— John

49

쉬운 솔루션 :

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 패키지를 제거하려고 시도했지만 놀랍게도 작동합니다. 하지만 시스템을 다시 시작했을 때 동일한 오류가 발생했기 때문에 보안 수준이 낮은 앱을 켜야했습니다 (작업 후 비활성화했습니다).

그런 다음 재미를 위해 방금 off (보안 수준이 낮은 앱)로 시도했고 vola 다시 작동했습니다!


1
1 단계와 2 단계는 매우 도움이되었습니다. 감사합니다! 나는 당신의 해결책을보기 전에 1 단계를 시도했지만 작동하지 않았지만 2 단계에서는 마술입니다!
— MissStack 2017 년

"smptTransport는 함수가 아닙니다"
— JWiley

나는 당신이 우리와 공유 한 방법으로 시도했지만 동일한 오류가 계속해서 발생합니다 {Error : connect ETIMEDOUT 74.125.68.108:465 at TCPConnectWrap.afterConnect [as oncomplete] (net.js : 1097 : 14) errno : ' ETIMEDOUT ', 코드 :'ECONNECTION ', syscall :'connect ', 주소 : '74 .125.68.108', 포트 : 465, 명령 : 'CONN'}
— Anwar Hussain

@AnwarHussain : Me도 같은 오류가 다시 발생합니다
— Pappa S

42

Gmail에 연결하려면 XOAuth2 토큰 을 사용해야합니다 . 걱정하지 마세요. 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);
      });
  });
};

9
Gmail 계정으로 NodeJS에서 이메일을 보내는 더 쉬운 솔루션이 있습니까?
— tonymx227 2013


passport.authorize가 수행하는 작업과 범위, 콜백 URL 등이 필요한 이유를 설명해 주시겠습니까? 왜 clientId 및 secret으로 할 수 없습니까?
— Ismail

passport.authorizepassport.authenticate현재 세션을 업데이트하지 않는다는 점 을 제외하면 비슷합니다 . callbackURLOAuth 핸드 셰이크 후 Google은 핸드 셰이크가 완료되도록 사용자를 리디렉션 할 위치를 알아야하기 때문에 통과해야합니다 .
— Laurent Perrin 2018


14

잘 작동했습니다.

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- 즐기십시오!


11

나에게도 같은 문제가 발생했습니다. localhost에서 시스템을 테스트 한 다음 다른 국가에있는 서버에 배포 한 다음 프로덕션 서버에서 시스템을 시도 할 때이 오류가 표시되었습니다. 나는 이것을 고치기 위해 시도했다.

  1. https://www.google.com/settings/security/lesssecureapps 사용 설정했지만 내 솔루션이 아닙니다.
  2. https://g.co/allowaccess 제한된 시간 동안 외부에서 액세스를 허용했는데 이로 인해 문제가 해결되었습니다.

2
g.co/allowaccess의 링크는 무엇 나를 위해 그것을 고정 (한 이미 활성화 lesssecureapps)이었다 - 감사합니다!

10

나를 위해 포트 및 보안을 사용하여 이러한 방식으로 작업하고 있습니다 (보안 설정없이 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);
}

모든 구성이 여기 에 나열 됩니다 (예제 포함).


10

위의 솔루션 중 어느 것도 나를 위해 일했습니다. 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
    }
}); 

고마워 친구 ! :) thissss ---> 호스트 : 'smtp.gmail.com', 포트 : 465, 보안 : true, Worked for Me
— Praveen Vishnu

@PraveenVishnu 문제 없습니다.이 답변에 투표하면 더 많은 사람들이 볼 수 있습니다. 그들에게도 도움이 될 수 있습니다.
— Hamid

안녕하세요, 저는 이것이 이미 오래된 것을 알고 있지만 serviceClient, privateKey 및 accessToken을 어디서 얻었습니까? 감사합니다.
— Aljohn Yamaro

@AljohnYamaro 메일 서비스에서 제공합니다. 제 경우에는 Gmail이었습니다. 자세한 내용은 여기에서 읽을 수 있습니다. stackoverflow.com/questions/36214968/…
— Hamid


9

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은 다른 주소를 사용하려고 할 때처럼 계정 이메일로만 대체하지 않습니다. 즉.

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

항상 this1을 사용합니다. 앱 비밀번호를 설정하려면 2 공장 인증을 설정해야합니다. 덜 안전한 것에 반대합니다.
— gdfgdfg

8

nodemailer-smtp-transportcreateTransport 내의 모듈을 사용하여 해결됩니다 .

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

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

4

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>



4

어떤 이유로 든 보안 수준이 낮은 앱 구성을 허용하는 것만으로도 보안 문자가 작동하지 않았습니다. IMAP 구성을 활성화하는 다른 단계를 수행해야했습니다.

Google 도움말 페이지 : https://support.google.com/mail/answer/7126229?p=WebLoginRequired&visit_id=1-636691283281086184-1917832285&rd=3#cantsignin

  • 오른쪽 상단에서 설정 설정을 클릭합니다.
  • 설정을 클릭하십시오.
  • 전달 및 POP / IMAP 탭을 클릭합니다.
  • "IMAP 액세스"섹션에서 IMAP 사용을 선택합니다.
  • 변경 사항 저장을 클릭하십시오.

3
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 유형을 추가해야합니다.


2

이전 버전의 nodemailer 0.4.1을 사용하고 있었는데이 문제가 발생했습니다. 0.5.15로 업데이트했고 모든 것이 잘 작동합니다.

변경 사항을 반영하도록 package.json 편집

npm install

3
이 경우 npm 업데이트 를 수행하는 것이 좋습니다 . 당신이 더 많은 방법에 대해 알고 싶다면 NPM 업데이트 및 설치 NPM 다른 - 다음이 답변을 참조하시기 바랍니다 - stackoverflow.com/questions/12478679/...
— 안토니 Akentiev

2

다음 사항에주의하십시오 : 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;

smtpTransport는 두 번 사용됩니다. 어느 것이 무엇입니까?
— Biranchi

정말 매우 명확 우선 하나는이 중포 기지 nowdays에서 완벽하게 작동이 설정을 사용하여 메일을 보내는 smtpTransport 설정하고, 두번째 버텍스를 만들기위한 것입니다
— 하밋 일 디림을

2

먼저 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");
        }
    });

내 응용 프로그램에서 작업

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.