이메일로 인증번호 받기 구현 | Nodemailer(with Gmail)

Bori·2022년 12월 26일
2

어쨌든 공부

목록 보기
9/40

Nodemailer

사용자에게 메일을 전송하기 위한 Node.js 모듈

Google 계정 보안 설정

gmail을 사용하기 위해서는 google 계정 보안 설정이 필요

  • google 계정 관리 > 보안 탭으로 이동

1. 2단계 인증 사용

  • Google에 로그인 > 2단계 인증을 선택하여 사용으로 변경합니다.

2. 앱 비밀번호 발급

  • 2단계 인증 하단에 있는 앱 비밀번호 발급 선택

  • 앱 선택 ⇒ 메일, 기기 선택 ⇒ 기타 하여 이름 설정

  • 기기용 앱 비밀번호가 생성됩니다.

  • 생성된 비밀번호는 Nodemailer의 환경변수에 넣어 사용합니다.

Nodemailer 설치

$ npm install --save nodemailer @types/nodemailer

.env 에 환경변수 설정

NODE_MAILER_ID=사용할 gmail
NODE_MAILER_PASSWORD=발급받은 기기용 앱 비밀번호 

SMTP Transport 설정

let transporter = nodemailer.createTransport(options[, defaults])
  • options : 연결 데이터를 정의하는 객체
  • defaults : 공유 옵션 지정(예: 모든 메시지의 동일에 주소 적용)
import nodemailer from 'nodemailer';

const smtpTransport = nodemailer.createTransport({
  service: 'gmail', // 사용할 메일 서비스
  auth: {
    user: process.env.NODE_MAILER_ID, // 환경변수로 설정한 메일 계정
    pass: process.env.NODE_MAILER_PASSWORD, // 기기용 앱 비밀번호
  },
  tls: {
    rejectUnauthorized: false,
  },
});

Message configuration 설정

var message = {
  from: "sender@server.com",
  to: "receiver@sender.com",
  subject: "Message title",
  text: "Plaintext version of the message",
  html: "<p>HTML version of the message</p>"
};
  • from : The email address of the sender.
  • to : Comma separated list or an array of recipients email addresses that will appear on the To: field
  • subject : The subject of the email
  • text : The plaintext version of the message as an Unicode string, Buffer, Stream or an attachment-like object ({path: ‘/var/data/…'})
  • html : The HTML version of the message as an Unicode string, Buffer, Stream or an attachment-like object ({path: ‘http://…'})
  • attachments : An array of attachment objects (see Using attachments for details). Attachments can be used for embedding images as well.
const mailOptions = {
	from: process.env.NODE_MAILER_ID,
	to: '메일 보낼 주소',
	subject: '메일 제목',
	html: `<strong>HTML 형식 메일 내용</strong>`,
	text: '텍스트 형식 메일 내용',
};

메일 보내기

transporter.sendMail(data[, callback])
  • data : defines the mail content (see Message Configuration for possible options)
  • callback : is an optional callback function to run once the message is delivered or it failed
  • err : is the error object if message failed
  • info : includes the result, the exact format depends on the transport mechanism used
await smtpTransport.sendMail(mailOptions, (error, responses) => {
	if (error) {
		res.status(400).json({ ok: false });
	} else {
		res.status(200).json({ ok: true });
	}
	smtpTransport.close();
});

최종 코드

import { NextApiRequest, NextApiResponse } from 'next';
import nodemailer from 'nodemailer';

const smtpTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: process.env.NODE_MAILER_ID,
    pass: process.env.NODE_MAILER_PASSWORD,
  },
  tls: {
    rejectUnauthorized: false,
  },
});

const handler = async (
  req: NextApiRequest,
  res: NextApiResponse
) => {
  const { email } = req.body;
  const payload = Math.floor(100000 + Math.random() * 900000) + '';

  if (email) {
    const mailOptions = {
      from: process.env.NODE_MAILER_ID,
      to: email,
      subject: 'Test 인증 메일',
      html: `<strong>인증번호는 ${payload} 입니다.</strong>`,
    };

    await smtpTransport.sendMail(mailOptions, (error, responses) => {
      if (error) {
        res.status(400).json({ ok: false });
      } else {
        res.status(200).json({ ok: true });
      }
      smtpTransport.close();
    });
  }

  return res.status(200).json({ ok: true });
};

export default handler;

참고

0개의 댓글