email인증을 쉽게 구현 할 수 있도록 하는 node.js 모듈이다.
npm install nodemailer
환경 설정을 둘다 사용함으로 선택 해준다.
SMPT 서버명과 SMPT port 번호를 기억 한다.
보안설정에서는 에플리케선 비밀번호 관리 -> 비밀번호 생성한다.
이렇게 생선한 비밀번호를 복사해서 저장 한다.
const nodemailer = require("nodemailer")
const transporter = nodemailer.createTransport({
service: 'naver',
host: 'smtp.naver.com', // SMTP 서버명
port: 465, // SMTP 포트
auth: {
user: process.env.NAVER_USER, // 네이버 아이디
pass: process.env.NAVER_PASS, // 발급하여 저장한 비밀 번호
},
})
module.exports = transporter
const router = require("express").Router()
const nodemailer = require("nodemailer")
const db = require("../modules/mysql")
const transporter = require("../modules/transporter")
router.post("/", async(req,res) => {
// Request Data
const emailValue = req.body.email
// Response Data
const result = {
"success": false,
"message": null,
"code": null
}
// Rules
const emailRule = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i
try {
if (!emailRule.test(emailValue)){
throw new Error("이메일 양식이 올바르지 않습니다.")
} else if (emailValue === null || emailValue === undefined || emailValue === "" || emailValue === "@") {
throw new Error("이메일 값이 올바르지 않습니다.")
}
const connection = await db.getConnection()
const sql = `
SELECT email FROM account WHERE email = ?
`
const values = [ emailValue]
const [rows] = await connection.query(sql, values)
if(rows.length !== 0){
throw new Error("중복된 메일입니다.")
}else{
const random_code = Math.floor(Math.random() * 1000000)// 6자기 인증코드 랜덤 추출
**transporter.sendMail**({
from: process.env.NAVER_USER ,//인증코드 발급자 이메일
to: emailValue,// 인증코드 받을 이메일 주소
subject: '[CarbonEye] 인증코드 안내',
html: `
<html lang="kr">
<body>
<div>
<div style="margin-top: 30px;">
<p style="font-size: 14px; color: #222222;">인증코드를 확인해주세요.</p>
<h3 style="font-size: 20px;">[${random_code}]</h3>
<p style="font-size: 14px; color: #222222;"> 이메일 인증코드를 발급해드립니다.</p>
</div>
</div>
</body>
</html>
//인증코드를 위한 간단한 html 양식
`
})
console.log(random_code,'메일 인증번호')
result.success = true
result.code = random_code
await connection.release()
res.send(result)
}
} catch(e) {
result.message = e.message
console.log("POST /mail API ERR : ", e.message)
}
})
module.exports = router