nodemailer

노드 서버에서 매우 쉽게 메일을 발송할 수 있는 외부 모듈이 존재한다.

npm install nodemailer

이렇게 설치를 하면 pacakage.json 에 현재 기준 5.0.0 이 설치된다.

공식 페이지

https://www.nodemailer.com/

사용법

사용법은 매우 간단하다.

모듈을 임포트 한 후 .createTransport 메소드를 수행한다.

let nodemailer = require('nodemailer');
nodemailer.createTransport(설정정보);

발송 준비를 위한 셋업을 한다.

이 Gmail 기준으로 설정정보에 들어가는 기본 값은 다음과 같이 설정할 수 있다.

{
    service : 'gmail',
    auth : {
        user : '계정명@gmail.com',
        pass : '패스워드'
    }
}

서비스에 따라서 포트를 따로 설정해주거나 개별 SMTP 서버를 기입할 수 도 있다.

메일 발송

transporter.sendMail(data[, callback]);

발송방법 또한 간단하다. .sendMail 메소드를 데이터를 넣어서 수행한다.

결과 콜백은 매우 다양한 형태로 제공된다.

리턴받은 객체들로 상황에 따른 후처리를 할 수 있다.

메일 발송 콜백

err : 에러 메세지 콜백

info : 결과에 대한 정보값

info.messageId : 결과 메세지 아이디

info.envelope : 결과 메세지

info.accepted : 전송이 승인 되었을 때

info.rejected : 전송이 반려되었을 때

info.pending : 전송이 대기 상태일 때

nodemailer-juice

또한 nodemailer-juice 를 설치하면 스타일을 인라인이 아닌 문서내에 첨부 할 수 있다.

그러면 컴파일 과정에서 자동으로 inline 화 시켜주기 때문에 매우 편리하다.

npm install nodemailer-juice

메일 발송 샘플

let transporter = nodemailer.createTransport(connections.mailer);
let inLineCss   = require('nodemailer-juice');
transporter.use('compile', inLineCss());

var contents =
  '<style>스타일</style>'+
  '<div>메일내용</div>';

var mailOptions = {
  from: 보내는사람,
  to: 받는사람,
  subject: 제목,
  html: contents
};

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

에러 메세지가 발생하는 경우

Error: Invalid login: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 https://support.google.com/mail/?p=BadCredentials a13sm2406148pfc.40 - gsmtp

에러 로그에 나오는 링크로 이동해 보면

  1. 계정 및 패스워드를 다시 확인

  2. 보안 수준 확인

이렇게 에러메세지가 나온다면 정말 계정과 비밀번호가 틀렸거나 아니면 보안 수준 설정을 하지 않은 경우이다.

보안수준 설정

https://myaccount.google.com/lesssecureapps

보안수준 설정부분에 가서 그림과 같이 보안 수준이 낮은 앱의 액세서를 허용해야 외부 서버에서 구글 메일을 발송 할 수 있다.

https://s3.ap-northeast-2.amazonaws.com/laerdream.github.io/2019-12-19/googlesecure.png