[javascript] Next.js를 사용하여 이메일 발송 기능을 구현할 수 있나요?
이메일을 발송하는 기능은 서버 사이드 로직이 필요하기 때문에, Next.js와 함께 서버 사이드 렌더링(SSR)을 활용할 수 있습니다.
다음은 Next.js에서 이메일 발송 기능을 구현하는 간단한 예제입니다.
- 먼저, 이메일을 발송하기 위해 필요한 패키지를 설치합니다.
npm install nodemailer
- 이메일 발송을 처리할 API 엔드포인트를 생성합니다.
// pages/api/send-email.js
import nodemailer from "nodemailer";
export default async function handler(req, res) {
if (req.method === "POST") {
const { to, subject, body } = req.body;
// 이메일을 발송하는 로직을 구현합니다.
try {
// SMTP 클라이언트 생성
const transporter = nodemailer.createTransport({
host: "smtp.example.com", // SMTP 호스트 설정
port: 587, // 포트 설정
secure: false, // 보안 설정
auth: {
user: "example@example.com", // 이메일 계정
pass: "password", // 이메일 계정 비밀번호
},
});
// 메일 옵션 설정
const mailOptions = {
from: "example@example.com", // 발신자 이메일
to: to, // 수신자 이메일
subject: subject, // 메일 제목
text: body, // 메일 내용
};
// 메일 발송
await transporter.sendMail(mailOptions);
res.status(200).json({ message: "이메일을 발송했습니다." });
} catch (error) {
console.error(error);
res.status(500).json({ message: "이메일 발송에 실패했습니다." });
}
} else {
res.status(405).json({ message: "POST 메서드만 허용됩니다." });
}
}
- 이제 클라이언트 측에서 해당 API 엔드포인트를 호출하여 이메일을 발송할 수 있습니다.
// 이메일 발송 요청 예제
fetch("/api/send-email", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
to: "recipient@example.com", // 수신자 이메일 주소
subject: "테스트 이메일", // 메일 제목
body: "안녕하세요, 이메일 발송 테스트입니다.", // 메일 내용
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
위 예제는 nodemailer
패키지를 사용하여 이메일을 발송하는 방법을 보여줍니다. SMTP 호스트, 포트, 인증 정보 및 이메일 옵션을 개인 환경에 맞게 수정하여 사용하십시오.
이렇게 하면 Next.js를 사용하여 이메일 발송 기능을 구현할 수 있습니다.