[Node.js] nodemailer 를 사용한 이메일 전송 (Gmail)

·2021년 11월 4일
0

친구방

목록 보기
1/1

Nodemailer

공식 사이트 : https://nodemailer.com/about/

  • 설치
npm i nodemailer
  • 이메일 전송 모듈(library에 저장)
// libray/emailSender.ts

import nodemailer from "nodemailer";

export default nodemailer.createTransport({
  service: "Gmail",
  auth: {
    user: process.env.EMAIL_ADDRESS,
    pass: process.env.EMAIL_PASS,
  },
	// 서명받지 않은 사이트의 요청도 받음
	tls: {
    rejectUnauthorized: false,
  },
});
  • 이메일 템플릿
// library/emailTemplate.ejs

<html>

<head>
</head>

<body>
    <div class="wrap">
				<p class="info_text">💡 회원가입 인증 코드</p>
        <div class="info_code">
            <%= certificationCode %>
        </div>
    </div>
</body>

</html>
  • 이메일 템플릿 설정
// src/service/authService.ts

let emailTemplate: string;
  ejs.renderFile(
    "src/library/emailTemplate.ejs",
    { certificationCode },
    (err, data) => {
      if (err) {
        console.log(err);
      }
      emailTemplate = data;
    }
  );
  • 이메일 전송
// src/service/authService.ts

const mailOptions = {
        front: process.env.EMAIL_ADDRESS,
        to: email,
        subject: "메일 제목",
        html: emailTemplate,
    };

emailSender.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.log(error);
      return -3;
    } else {
      console.log("success");
    }
    emailSender.close();
  });


ERROR

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 p15sm161302pjh.1 - gsmtp

0개의 댓글