programming/node.js

[Node.js] gmail로 이메일 전송하기

LeeBorn 2019. 11. 21. 00:00
반응형

node.js

node.js 이메일 보내기

https://www.w3schools.com/nodejs/nodejs_email.asp

 

Node.js Email

Node.js Send an Email The Nodemailer Module The Nodemailer module makes it easy to send emails from your computer. The Nodemailer module can be downloaded and installed using npm: C:\Users\Your Name>npm install nodemailer After you have downloaded the Node

www.w3schools.com

해당 튜토리얼을 진행하면 이메일을 보낼 수 있는 방법이 있다.

구글 메일을 사용하는데 아래와 같은 에러가 뜨면서 보내지지 않는다.

1
2
3
4
5
6
7
{ Error: Invalid login: 535-5.7.8 Username and Password not accepted. Learn more at
...
  code: 'EAUTH',
  response:
   '535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8  ...
  responseCode: 535,
  command: 'AUTH PLAIN' }

 

보안 수준이 낮은 앱이라서 허용되지 않는다.

로그인 시도 차단

 

보안 수준이 낮은 앱 액세스 

이를 해결해 주려면 잠시 보안을 낮춰야 한다.

https://myaccount.google.com/lesssecureapps

 

로그인 - Google 계정

하나의 계정으로 모든 Google 서비스를 Google 계정으로 로그인

accounts.google.com

해당 주소로 접근하면 보안 수준이 낮은 앱을 허용해 줄 수 있다.

잠깐 테스트용으로만 열어주고 다시 원상태로 바꿔주는 게 좋을 것 같다.

그러면 아래와 같이 메일을 보낼 수 있다.

 

계정정보 실행 시 입력받기

그리고 해당 튜토리얼 소스에는 메일 계정 정보가 하드코딩 되어있다.

이전 게시물 [node.js 시작 시 실행 인자 받는 법]을 참고해서 실행 시 계정 정보를 입력하도록 변경했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var nodemailer = require('nodemailer');
 
const USER_NAME    = process.argv[2];
const USER_PASS    = process.argv[3];
const TO_USER_NAME = process.argv[4];
 
var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: USER_NAME,
    pass: USER_PASS
  }
});
 
var mailOptions = {
  from: USER_NAME,
  to: TO_USER_NAME,
  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);
  }
});

 

반응형