Node.js

[Node] nodemailer로 이메일 전송하기

hazel__ 2022. 5. 29. 02:46

사물함 대여 서비스를 운영하던 중 장기 대여 연체자가 생긴 문제가 발생했다.

슬랙봇으로 대여 및 반납, 연체 정보를 메세지를 전송하려고 했으나, 승인 지연으로 부득이하게 이메일로 연체 알림을 보내기로 했다.

이에 따라 연체자 명단을 이용하여 메일을 전송하는 코드를 작성했다.

 

 

Nodemailer :: Nodemailer

Nodemailer Nodemailer is a module for Node.js applications to allow easy as cake email sending. The project got started back in 2010 when there was no sane option to send email messages, today it is the solution most Node.js users turn to by default. npm i

nodemailer.com

 

nodemailer는 이메일을 쉽게 보낼 수 있는 모듈이다.

Unicode를 지원하여 이모지를 전송할 수 있고, HTML, Text 등을 전송할 수 있다.

npm으로 설치할 수 있다.

 

💡 Node.js v6.0.0 이상을 지원한다.

 

1. nodemailer 설치

npm install nodemailer

 

2. 옵션 설정하기

const mailer = require('nodemailer');

let transporter = mailer.createTransport({
  service: 'gmail',
  host: 'smtp@gmail.com',
  auth: {
    user: USER_EMAIL,
    pass: PASS_TOKEN,
  },
  secure: true, //TLS
  port: 465,
});

createTransport 메서드를 사용하여 옵션을 설정하고, 전송 객체를 생성한다.

 

PASS

pass 값은 gmail 비밀번호가 아니다!!

google 계정관리 ➡ 보안 ➡ 앱 비밀번호

위의 경로로 이동해서 앱 비밀번호를 발급받아 사용한다.

 

앱 비밀번호로 로그인 - Google 계정 고객센터

도움이 되었나요? 어떻게 하면 개선할 수 있을까요? 예아니요

support.google.com

 

3. 메일 전송하기

const sendMail = (email) => {
  let mailOptions = {
    from: USER_EMAIL,
    to: email,
    subject: '사물함 연체 알림',
    text: '연체되었습니다!!!',
  };

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

sendMail 메서를 사용하여 메일을 전송할 수 있다.

 

4. 다중 수신자

메일의 수신자가 많은 경우, to 의 값에 콤마(,)와 공백( )을 기준으로 문자열로 나열되어 보낼 수 있다.

to: 'abc@gmail.com, def@naver.com, ...'

 

위와 같이 이메일을 전송하는 경우, 실제로 받은 메일에서 모든 수신자의 목록을 볼 수 있다.

이를 해결하기 위해서는 to 에 문자열을 연결해서 사용하지 않고, 하나씩 전송하도록 수정했다.

const mailing = () => {
  const mail = ['abc@gmail.com', 'def@naver.com', ...];
  mail.forEach(person => {
    sendMail(person);
  });
};