2014-10-04 7 views
11

서버가 실제로 이메일을 보낼 수 있는지 테스트 할 수 있도록 로컬 (http://localhost:8080)의 기본 NodeJS 서버를 설정했습니다.nodemailer를 사용하여 Node.js를 통해 이메일을 보내지 않습니다.

나는 (내가 틀렸다면 수정하시기 바랍니다) 제대로 SMTP 옵션을 이해한다면, 내가 직접, 또는 내가 이메일을 보낼 수있는 사람의 이메일 계정으로 내 서버에서 이메일을 보내려고 할 수 있습니다 , 여전히 Node.js를 사용하지만 실제 이메일 계정 (이 경우 제 개인 Gmail 계정)을 통해 을 사용합니다 (예 : SMTP 사용). 이 옵션을 사용하려면 NodeJS를 통해 해당 계정에 원격으로 로그인해야합니다.

아래의 서버에서 실제로 NodeJs를 사용하여 내 개인 전자 메일 계정에서 내 개인 전자 메일 계정으로 전자 메일을 보내려고합니다.

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); 

그러나, 그것은 작동하지 않습니다 :

여기 내 간단한 서버입니다. 나는 구글이 말한 이메일을 받았다.

Google Account: sign-in attempt blocked If this was you You can switch to an app made by Google such as Gmail to access your account (recommended) or change your settings at https://www.google.com/settings/security/lesssecureapps so that your account is no longer protected by modern security standards.

nodemailer GitHub 페이지에서 위의 문제에 대한 해결책을 찾을 수 없었다. 누구든지 해결책/제안이 있습니까?

감사합니다. :-)

답변

25

답변은 google의 메시지에 있습니다.

사용 보안 수준이 낮은 앱의 액세스를 설정하고

에 응답

I'm actually simply following the steps from the nodemailer github page so there are no errors in my code

나는 nodemailer의 GitHub의 페이지로 참조하고,이 코드 조각 것 : nodemailer.createTransport("SMTP" :

var transporter = nodemailer.createTransport({ 
service: 'Gmail', 
auth: { 
    user: '[email protected]', 
    pass: 'userpass' 
} 
}); 

그것은 당신이 가지고 있다는 사실에, 사용자 코드에서 약간 다릅니다. SMTP 매개 변수를 제거하면 제대로 작동합니다. 또한, http 서버에 캡슐화하는 이유는 무엇입니까? 다음 작품 :

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

console.log('created'); 
transporter.sendMail({ 
from: '[email protected]', 
    to: '[email protected]', 
    subject: 'hello world!', 
    text: 'hello world!' 
}); 
+0

일부 nodemailer 설정을 통해 그 I 어쩌면 내려다 .. 어쩌면 몇 가지 추가 인증 속성을 설정 .. 감사합니다! –

+0

지금 사용 설정하면 Google에서 알림을받는 데 오랜 시간이 걸리지 만 이메일이 전송되지 않으므로 여전히 작동하지 않습니다 ... –

+0

다른 'to'및 'from'주소를 사용해보십시오. 과거 Gmail과 다른 수신자가 비슷한 문제를 겪었습니다. – xShirase

2

는 (있는 경우) 오류 메시지가 표시 콜백 함수를 (그들은 nodemailer의 GitHub의 페이지에하지 않을) 구현하기가 편리 목적을 디버깅하십시오.

는 "nodemailer 1.0이 깨는 변화 때문에 0 같은데 :

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

그것은 제대로 작동하지 않는 나를 ... 내 문제를 해결 최신 버전을 밝혀 주었다.7 대신 사용해야합니다 http://www.nodemailer.com/

메시지 12/17/15의로 nodemailer에 게시 : 깨는 변화가로

1.0 0.7 이하에서 Nodemailer를 업그레이드하지 마십시오. 원하는만큼 0.7 분기를 계속 사용할 수 있습니다. 0.7 here 설명서를 참조하십시오 "

나는이 대답 here

0

나를위한 일이 코드를 시도 발견

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

    var fromEmail = '[email protected]'; 
    var toEmail = '[email protected]'; 

    var transporter = nodemailer.createTransport({ 
    host: 'domain', 
    port: 587, 
    secure: false, // use SSL 
    debug: true, 
     auth: { 
     user: '[email protected]', 
     pass: 'userpassword' 
     } 
    }); 
    transporter.sendMail({ 
     from: fromEmail, 
     to: toEmail, 
     subject: 'Regarding forget password request', 
     text: 'This is forget password response from youapp', 
     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 sedning email'); 
      console.dir({success: true, existing: false, sendError: false}); 
      console.dir(response); 
      res.end('Successful in sedning email'); 
     } 
    }); 
}).listen(8000); 
console.log('Server listening on port 8000'); 

응답 :.. 사람들을 위해

Successful in sedning email 
{ success: true, existing: false, sendError: false } 
{ accepted: [ '[email protected]' ], 
    rejected: [], 
    response: '250 2.0.0 uAMACW39058154 Message accepted for delivery', 
    envelope: 
    { from: '[email protected]', 
    to: [ '[email protected]' ] }, 
    messageId: '[email protected]' } 
7

누가 실제로 OAuth2를 사용하고 싶거나 앱을 "덜 안전하게"만들고 싶지 않으면로이 작업을 수행 할 수 있습니다.

  1. 검색하려면 google API console에서 "Gmail이 API"를 클릭은
  2. https://developers.google.com/gmail/api/quickstart/nodejs의 단계에 따라 "사용". https://nodemailer.com/smtp/oauth2/
  3. 에서 문제 해결의 제안으로 quickstart.js 파일에서, (2), 생성 된 JSON 파일이 acessToken, refreshToken 포함됩니다의 단계를 수행 한 후 제공되는 퀵 스타트 JS 파일에 ['https://mail.google.com/']['https://www.googleapis.com/auth/gmail.readonly']에서 SCOPES VAR을 변경, 및 expires 속성은 OAuth2 Examples for Nodemailer

에 다음과 같은

let transporter = nodemailer.createTransport({ 
    service: 'Gmail', 
    auth: { 
     type: 'OAuth2', 
     user: '[email protected]', 
     clientId: '000000000000-xxx0.apps.googleusercontent.com', 
     clientSecret: 'XxxxxXXxX0xxxxxxxx0XXxX0', 
     refreshToken: '1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx', 
     accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x', 
     expires: 1484314697598 
    } 
}); 
등으로 OAuth2 인증을 사용할 수있는이 방법이 필요210 대신 일반 텍스트로 Gmail 비밀번호를 저장하고 계정 보안을 낮추십시오.

+0

더 이상 유효하지 않으며 해당 파일에 accessToken 및 refreshToken이 더 이상 존재하지 않습니다. – CaptRisky

+0

작동하도록하려면이 answer 전송 정의 (accessToken 및 expires를 지정하지 않고)와 새로 고침 토큰을 얻기 위해 Google의 oauth 놀이터를 사용하는이 게시물 : https : // medium.com/@ pandeysoni/nodemailer-service-in-node-js-using-smtp-and-xoauth2-7c638a39a37e – apricity

+0

내 gmail-nodejs-quickstart.json에 SCOPES 변수가 없습니다. – Kirby

1

위의 답변이 효과가 있지만 다음 글에서 TWO 단계까지 Gmail의 보안을 줄일 수 있다는 점을 알려드립니다.

1 단계

Google Account: sign-in attempt blocked If this was you You can switch to an app made by Google such as Gmail to access your account (recommended) or change your settings at https://www.google.com/settings/security/lesssecureapps so that your account is no longer protected by modern security standards.

STEP # 2

In addition to enabling Allow less secure apps, you might also need to navigate to https://accounts.google.com/DisplayUnlockCaptcha and click continue.

3

난 그냥 내 도메인을 설정 : 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: '[email protected]', 
     pass: 'xxx' 
    } 
}); 

let mailOptions = { 
    from: '"xxx" <[email protected]>', 
    to: '[email protected]', 
    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 템플릿 (이메일.EJS) :

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

확인 :

이 좋은 하루 가지고 이메일을 보낼 이메일에 l.com Gmail 이메일로는

  • 변경 [email protected])

  • 1

    Google 인증을 위해 앱 비밀번호 만 필요하며 코드에서 Google 비밀번호를 바꿉니다. 는 여기 https://myaccount.google.com/apppasswords

    샘플 코드 : 나는 내가 무시할 수 있다고 생각 .. 그것을 생각하는 것은 실제로 내 계정에 더 취약한 수도 피하기 위해 원

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

    screenshot

    +0

    이유를 모르겠지만 이건 내 스테이징 환경이 아니라 localhost에서 작동합니다. –

    관련 문제