이전에 GOAT 데정현씨가 우리 서비스에 적용한 걸 보고 어깨너머로 코드를 뜯어보며 '아하 이런 것이군...' 하고 봤던 노드메일러... 이번에는 내가 사용해야 하기 때문에 진짜로 정리해본다! 이전에도 도 정리 한 번 해야지~ 하고선 그대로 넘어가버렸는데 ㅋㅋㅋ 이번에 후회함... 그래서 본격적으로 Nodemailer를 보며 정리하는 노드메일러 🤗
npm install nodemailer
로 설치!
: 공식 문서 홈페이지에서도 써있지만 노드메일러는 Node.js 애플리케이션을 위한 모듈로, 쉽게 이메일을 보낼 수 있게 해준다. (근데 안 쉽기도 함... 금요일에 왜 애먹었지 나...)
(사실 이거 뭔지 몰라서 검색해봤는데 대충 한 줄 요약 이라는 뜻이라고 함)
메시지를 보내기 위한 작업은 크게 세 가지로 나눌 수 있다
SMTP 또는 다른 운송 매커니즘을 사용하여 Nodemailer 전송기를 만든다
메시지 옵션을 설정한다 (누가 누구에게 무엇을 보내는지)
이전에 생성된 전송기의 sendMail()
메서드를 사용하여 메시지 객체를 전달한다.
이메일을 보내기 위해서는
transporter
객체를 만들어야 한다
이 때 transporter를 만드는 방법은 두 가지가 있는데 보통은 SMTP 방식으로 메일을 보내게 된다.
transporter
만들기let transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
port: 587,
secure: false,
requireTLS: true,
auth: {
user: process.env.NODEMAILER_USER,
pass: process.env.NODEMAILER_PASS,
},
});
auth에는 내가 메일을 보내는데 사용할 계정의 이메일 주소와 비밀번호를 입력해주면 된다. gmail 계정의 일반 비밀번호가 보안 문제로 인해 사용할 수 없을 수도 있기 때문에 앱 비밀번호를 설정한 후, 생성된 앱 비밀번호로 비밀번호를 바꿔주어야 한다.
sendMail()
함수 만들기const sendMail = async (to: string, subject: string, html: string) => {
try {
await transporter.sendMail({
from: process.env.NODEMAILER_USER,
to,
subject,
html,
});
} catch (error) {
console.error(`Fail to send email to ${to}: ${error.message}`);
error.statusCode = 500;
throw error;
}
};
from은 메일을 보낼 계정, to는 받을 계정, subject는 제목, html은 들어갈 내용이다.
const contactMail = async (req: Request, res: Response) => {
try {
const { email, title, phone, text } = req.body;
await sendMail(
email,
title,
`<h1>이 메일을 받는 즉시 ${phone} 번호로 회신 바랍니다.</h1><br>${text}`,
);
} catch (error) {
console.error(error);
res
.status(500)
.json({ message: '메일 전송에 실패했습니다.', status: false });
}
};
기능 테스트를 위해서 임시로 만들었다. post 방식으로 보낼 것이기 때문에 body에 메일을 보낼 이메일 주소(email
), 이메일 제목(title
), 그리고 내용(text
)를 받아온 후... 위에서 만든 sendMail()
함수를 불러와 각각 to
, subject
, html
인자로 넣어주면 된다.
요렇게 테스트를 해보면!
개빡침... 왜 안됨?...
Fail to send email to topgdvidsyb@gmail.com: Invalid login: 535-5.7.8 Username and Password not accepted. For more information, go to
535 5.7.8 https://support.google.com/mail/?p=BadCredentials x5-20020a170902ea8500b001cfc1b93179sm4470339plb.232 - gsmtp
Error: Invalid login: 535-5.7.8 Username and Password not accepted. For more information, go to
535 5.7.8 https://support.google.com/mail/?p=BadCredentials x5-20020a170902ea8500b001cfc1b93179sm4470339plb.232 - gsmtp
at SMTPConnection._formatError (D:\GitHub\gangMailer\node_modules\nodemailer\lib\smtp-connection\index.js:790:19)
at SMTPConnection._actionAUTHComplete (D:\GitHub\gangMailer\node_modules\nodemailer\lib\smtp-connection\index.js:1564:34)
at SMTPConnection.<anonymous> (D:\GitHub\gangMailer\node_modules\nodemailer\lib\smtp-connection\index.js:546:26)
at SMTPConnection._processResponse (D:\GitHub\gangMailer\node_modules\nodemailer\lib\smtp-connection\index.js:969:20)
at SMTPConnection._onData (D:\GitHub\gangMailer\node_modules\nodemailer\lib\smtp-connection\index.js:755:14)
at TLSSocket.SMTPConnection._onSocketData (D:\GitHub\gangMailer\node_modules\nodemailer\lib\smtp-connection\index.js:193:44)
at TLSSocket.emit (node:events:514:28)
at TLSSocket.emit (node:domain:488:12)
at addChunk (node:internal/streams/readable:376:12)
at readableAddChunk (node:internal/streams/readable:349:9) {
code: 'EAUTH',
response: '535-5.7.8 Username and Password not accepted. For more information, go to\n' +
'535 5.7.8 https://support.google.com/mail/?p=BadCredentials x5-20020a170902ea8500b001cfc1b93179sm4470339plb.232 - gsmtp',
responseCode: 535,
command: 'AUTH PLAIN',
statusCode: 500
}
계속해서 이 에러가 발생하는 중이다. 대체 왤까... 아니 진짜로 이메일, 비밀번호 확인 오지게 했다고 ㅠㅠㅠ 왜 안되는 걸까... 내가 뭘 잘못한 걸까... 기능테스트 장렬하게 실패... 속상... 아니 지난번엔 왜 된건데...
저녁먹기 전까지 해결이 될지 모르겠어서 일단 이대로... 글 업로드... 흑흑...