[AWS SES] 다른 도메인을 발송자로 설정하여 Gmail로 발송하기

2021.06.01 - [AWS/SES (Simple Email Service)] - AWS SES 세팅 및 Gmail 리다이렉션 설정 AWS SES 세팅 및 Gmail 리다이렉션 설정 Intro 현재 회사에서 사용하고 있는 메일서비스는 후이즈메일을 사용하고 있다...

charming-kyu.tistory.com

이전 편 에서 내 도메인을 발송자로 설정해 Gmail에서 발송이 가능하니 오늘은 node.js express 환경에서 회원가입 인증메일을 발송하는 API를 만들고자 한다. 만약 본인의 AWS SES가 Sandbox 환경이라면 1일 100건의 발송 제한 및 이메일 인증을 받은 계정으로만 메일을 발송할 수 있기 때문에 발신에 사용할 Email을 먼저 인증해야 한다는 점 참고 바란다.

npm install nodemailer, @aws-sdk/client-ses, ejs, crypto

npm 명령어로 4가지의 모듈을 받는다.
nodemailer - SMTP 메일 발송을 도와줄 라이브러리
@aws-sdk/client-ses - AWS에서 제공하는 SES SDK
ejs - ejs를 html로 바꿔줄 라이브러리
crypto - 랜덤으로 숫자를 생성해 줄 라이브러리 Math.random() 은 암호학적으로 안전한 난수를 제공하지 않으므로, 보안과 관련된 어떤 것에도 이 함수를 사용해서는 안 된다.

register.ejs

<html>
  <body>
    <div style="font-size:13px;">
		회원가입 해주셔서 감사합니다.
	</div>
	<div style="font-size:13px;">
	  해당 메일은 <%= email %>이 정확한 이메일 주소인지 확인하는 메일입니다.
	</div>
    <div style="font-size:18px;">
      인증코드는 [ <%= code %> ] 입니다.
    </div>
  </body>
</html>

index.js

const nodemailer = require("nodemailer");
const aws = require("@aws-sdk/client-ses");
const ejs = require('ejs');
const crypto = require("crypto");
process.env.AWS_ACCESS_KEY_ID = 'EXAMPLEIDKEY'; // aws access key
process.env.AWS_SECRET_ACCESS_KEY = 'EXAMPLEACCESSKEYPASSWORD' // aws secret access key
router.post('/mail', (req, res, next) => {
  //Request body에 실어져 있는 데이터 가져오기
  const userEmail = req.params.userEmail;
  
  //해시코드 생성
  const code = crypto.randomBytes(3).toString('hex');
	//DB에 해당 유저 튜플에 코드 값 UPDATE 코드 .. 생략
  
  //발송 할 ejs 준비
  let emailTemplate;
  ejs.renderFile('./registerVerify.ejs',  //ejs파일 위치 
                 { email: userEmail, code: code}, (err, data) => { //ejs mapping
            if (err) { console.log(err) }
            emailTemplate = data;
      });
  //ses ready
  const ses = new aws.SES({
        apiVersion: "2010-12-01",
        region: "us-east-1", //AWS SES Region 수정
  });
    // create Nodemailer SES transporter 
    // 이 때 process.env에 AWS_ACCESS_KEY_ID와 AWS_SECRET_ACCESS_KEY를 확인한다.
  let transporter = nodemailer.createTransport({ 
        SES: { ses, aws },
  });
    // send mail
  transporter.sendMail(
      {
          from: "닉네임<welcome@example.com>",
          to: target,
          subject: "[example] 회원가입 인증메일 입니다.",
          html: emailTemplate,
      },
      (err, info) => {
          if (err) {
              console.log(err);
              res.status(500).json(err);
          }
      }
  );
  res.status(200).json({
    code: 200,
	message: '발송 성공'
  });
});

이후 인증은 DB에 저장된 key 값을 비교해주면 된다.
필자는 ejs 템플릿을 좀 수정하여 적용하였다.