Nodemailer로 인증 관련 이메일 보내기

Jiwon Yang·2019년 12월 28일
3
post-thumbnail

사용자가 회원가입 시, 입력한 이메일이 유효한지 검증하는 상황 혹은 사용자에게 임시 비밀번호를 전달하는 경우 등등 서버 측에서 사용자에게 이메일을 보내야하는 경우가 존재합니다! 이때, Node에서 사용할 수 있는 유용한 모듈이 바로 Nodemailer 입니다 📧

1. Nodemailer 란?

공식사이트 에서 Nodemailer의 특징을 살펴볼 수 있는데요! 우선, Node.js 애플리케이션에서 메일을 쉽게 보낼 수 있도록 도와주는 모듈이라고 합니다.

  • Emoji를 포함한 Unicode를 지원합니다.
  • 윈도우도 지원하고요!
  • Plain text는 물론이고, HTML content를 사용합니다.
  • 이외에도 메시지에 다양한 것들을 첨부할 수 있죠!
  • RCE(Remote Code Execution) 취약점따위 존재하지 않습니다.
  • DKIM을 이용한 sign 방식을 사용하고요
  • SMTP 를 포함한 다양한 전송 방식을 지원합니다.
  • OAuth2 인증방식을 지원합니다.

2. SMTP 및 TLS 란?

1) SMTP

SMTP is the main transport in Nodemailer for delivering messages. 
SMTP is also the protocol used between different email hosts, so its truly universal. 
Almost every email delivery provider supports SMTP based sending, even if they mainly push their API based sending. 
APIs might have more features but using these also means vendor lock-in 
while in case of SMTP you only need to change the configuration options to replace one provider with another and you’re good to go.
  • 공식문서에서 설명한 부분을 100% 이해가 가진 않는다 ㅠㅠ

2) TLS

2. 실습

1) 이메일 생성

  • Gmail은 하루 최대 전송량이 500이라서 저는 Naver 계정을 만들었습니다!
  • 네이버 계정 생성 후 아래와 같이 SMTP 설정을 해주세요

2) nodemailer 설정

  • 설치
npm i nodemailer
  • 메일을 보낼 transporter 객체 생성
let transporter = nodemailer.createTransport(configuration[, mail options])
  • 메일 보내기
transporter.sendMail(data[, callback])
  • 전체 예시 코드
const nodemailer = require('nodemailer')
async sendMail(email) {
    try {
      const mailConfig = {
        service: 'Naver',
        host: 'smtp.naver.com',
        port: 587,
        auth: {
          user: process.env.MAIL_EMAIL,
          pass: process.env.MAIL_PASSWORD
        }
      }
      let message = {
        from: process.env.MAIL_EMAIL,
        to: email,
        subject: '이메일 인증 요청 메일입니다.',
        html: '<p> 여기에 인증번호나 token 검증 URL 붙이시면 됩니다! </p>'
      }
      let transporter = nodemailer.createTransport(mailConfig)
      transporter.sendMail(message)
    } catch (error) {
      console.log(error)
    }
  }

3. 남은 문제들

  • pool connection
  • secure : true 시, TLS 처리
profile
안녕하세요 양지원입니다

1개의 댓글

comment-user-thumbnail
2021년 9월 17일

함수를 async로 만들었는데 await을 안쓰길래 보니까 sendMail 함수가 Promise 함수군요

답글 달기